02051211.c

来自「用C语言实现的一个链表的插入程序」· C语言 代码 · 共 83 行

C
83
字号
#include<stdio.h>
#include<stdlib.h>
struct listNode{
  char data;
  struct listNode * nextPtr;
};
typedef struct listNode LISTNODE;
typedef LISTNODE * LISTNODEPTR;

void printList(LISTNODEPTR);
void instructions(void);
main()
{
      LISTNODEPTR startPtr=NULL,currentPtr=NULL,lastPtr=NULL;
      int choice;
      char item;
      instructions();
      printf("?");
      scanf("%d",&choice);
      while(choice!=2){
         switch (choice){
         case 1:
           printf("Enter a character:");
           scanf("\n%c",&item);
           currentPtr=malloc(sizeof(LISTNODEPTR));
           if(currentPtr!=NULL){
             currentPtr->data=item;
             currentPtr->nextPtr=NULL;
                          
             if(startPtr==NULL){
                startPtr=currentPtr;
                lastPtr=currentPtr;
             }
             else{
                lastPtr->nextPtr=currentPtr;
                lastPtr=currentPtr;
                }
             }
         else
           printf("%c not inserted.No memory available.\n",item);
           
           
           printList(startPtr);
           break;
         
         default:
           printf("Invalid choice.\n\n");
           instructions();
           break;
      }
      printf("?");
      scanf("%d",&choice);
      }
      printf("End of run.\n");
      system("PAUSE");
      return 0;
}
void instructions(void)
{
     printf("Enter your choice:\n"
            "1 to insert an element into the list.\n"
            "2 to end.\n");
}

      

void printList(LISTNODEPTR currentPtr)
{
     if(currentPtr==NULL)
        printf("List is empty.\n\n");
     else{
        printf("The list is:\n");
     while(currentPtr!=NULL){
        printf("%c-->",currentPtr->data);
        currentPtr=currentPtr->nextPtr;
     }
     printf("NULL\n\n");
}
}

       
     

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?