zoukankan      html  css  js  c++  java
  • 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("
    The list is NULL!
    ");
    38    else
    39    {   printf("
    Head");
    40        do { printf("->%d",p->data);  p=p->next;  } while(p!=NULL);
    41        printf("->End
    ");
    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("
    The list before inserting:
    ");  outlist(head);
    49    printf("
    Enter a number :  ");  scanf("%d",&x);
    50    fun(head,x);
    51    printf("
    The list after inserting:
    ");  outlist(head);
    52 }
  • 相关阅读:
    JS进阶篇--函数防抖(debounce)
    vue注册全局组件分页
    vue下拉框清空
    vue中的watch监听
    五:request和response的使用
    四:servlet最终形态
    三:登录功能实现,servlet
    二:Tomcat与登录
    一:JavaWeb
    Linux安装JAVA并且配置环境
  • 原文地址:https://www.cnblogs.com/ming-4/p/10517742.html
Copyright © 2011-2022 走看看