C语言:有序递增链表的插入问题。

//已建立一个带头节点的单向链表,链表中的各结点按结点数据域中的数据递增有序连接。fun函数:把形参x的值放入一个新结点并插入链表中,使插入的各个数据域的数据仍保持递增有序。

 1 #include    <stdio.h>
 2 #include    <stdlib.h>
 3 #define    N    8
 4 typedef  struct list
 5 {  int  data;
 6    struct list  *next;
 7 } SLIST;
 8 void fun( SLIST  *h, int  x)
 9 {  SLIST  *p, *q, *s;
10    s=(SLIST *)malloc(sizeof(SLIST));//申请内存
11 /**********found**********/
12    s->data=x;
13    q=h;
14    p=h->next;
15    while(p!=NULL && x>p->data) {
16 /**********found**********/
17       q=p;
18       p=p->next;往后遍历,直到x的大小合适
19    }
20    s->next=p;//插入操作,在q和p之间插入s
21 /**********found**********/
22    q->next=s;
23 }
24 SLIST *creatlist(int  *a)
25 {  SLIST  *h,*p,*q;      int  i;
26    h=p=(SLIST *)malloc(sizeof(SLIST));
27    for(i=0; i<N; i++)
28    {  q=(SLIST *)malloc(sizeof(SLIST));
29       q->data=a[i];  p->next=q;  p=q;
30    }
31    p->next=0;
32    return  h;
33 }
34 void outlist(SLIST  *h)
35 {  SLIST  *p;
36    p=h->next;
37    if (p==NULL)  printf("\nThe list is NULL!\n");
38    else
39    {   printf("\nHead");
40        do { printf("->%d",p->data);  p=p->next;  } while(p!=NULL);
41        printf("->End\n");
42    }
43 }
44 void main()
45 {  SLIST  *head;      int  x;
46    int  a[N]={11,12,15,18,19,22,25,29};
47    head=creatlist(a);
48    printf("\nThe list before inserting:\n");  outlist(head);
49    printf("\nEnter a number :  ");  scanf("%d",&x);
50    fun(head,x);
51    printf("\nThe list after inserting:\n");  outlist(head);
52 }

猜你喜欢

转载自www.cnblogs.com/ming-4/p/10517742.html