单链表创建插入删除打印反转

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
 
 
struct Node
{
 int score;
 struct Node *next;
};
 
 
typedef struct Node ListNode;
 
 
ListNode *CreateList(int n)
{
 ListNode *head;
 ListNode *p,*pre;
 int i;
 head=(ListNode *)malloc(sizeof(ListNode));
 head->next=NULL;
 pre=head;
 for(i=1;i<=n;i++)
  {
   p=(ListNode *)malloc(sizeof(ListNode));
   scanf("%d",&p->score);
   pre->next=p;
   pre=p;
  }
 p->next=NULL;
 return head;
}
 
 
void PrintList(ListNode *h)
{
 ListNode *p;
 p=h->next;
 while(p)
  {
   printf("%d",p->score);
   p=p->next;
   printf("\n");
  }
}
 
 
void InsertList(ListNode *h,int i,int e,int n)
{
 ListNode *q,*p;
 int j;
 if(i<1 || i>n+1)
  printf("Error! Please input again.\n");
 else
  {
   j=0;
   p=h;
   while(j<i-1)
    {
     p=p->next;
     j++;
    }
   q=(ListNode *)malloc(sizeof(ListNode));
   q->score=e;
   q->next = p->next;
   p->next=q;
  }
}
 
 
void DeleteList(ListNode *h, int i, int n)
{
 ListNode *p,*q;
 int j;
 int score;
 if(i<1 || i>n)
  printf("Error!");
 else
  {
   j=0;
   p=h;
   while(j<i-1)
    {
     p=p->next;
     j++;
    }
   q=p->next;
 
 
   p->next=q->next;
   score=q->score;
   free(q);
   printf("score=%d\n",score);
  }
}
 
 
void ReverseList(ListNode *head)
{
 
 
    ListNode *p1,*p2,*p3;
        if(head==NULL || head->next ==NULL)
        return ;
        p1=head->next;
        p2=p1->next;
        p1->next =NULL;
        while(p2)
        {
            p3=p2->next;
            p2->next=p1;
            p1=p2;
            p2=p3;
        }
        head->next=p1;
        PrintList(head);
 
 
}
 
 
void main()
{
 ListNode *h;
 int i = 1, n, score;
 while ( i )
  {
   printf("1--creat\n");
   printf("2--add\n");
   printf("3--delte\n");
   printf("4--print\n");
   printf("5--reverseList");
   printf("0--exit\n");
   scanf("%d",&i);
   switch(i)
    {
     case 1:
      printf("n=");
      scanf("%d",&n);
      h=CreateList(n);
      printf("the list elements is:\n");
      PrintList(h);
      break;
 
 
     case 2:
      printf("input the position. of insert element:");
      scanf("%d",&i);
      printf("input score of the student:");
      scanf("%d",&score);
      InsertList(h,i,score,n);
      printf("list elements is:\n");
      PrintList(h);
      break;
 
 
     case 3:
      printf("input the position of delete element:");
      scanf("%d",&i);
      DeleteList(h,i,n);
      printf("list elements in : \n");
      PrintList(h);
      break;
 
 
     case 4:
      printf("list element is : \n");
      PrintList(h);
      break;
     case 5:
       ReverseList(h);
       break;
     case 0:
      return;
      break;
     default:
      printf("ERROR!Try again!\n");
    }
  }
}
 
发布了12 篇原创文章 · 获赞 6 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/huaweizte123/article/details/53907397