线性表基本操作和简单程序——c语言

来源:互联网 发布:宿迁网络问政如何投诉 编辑:程序博客网 时间:2024/05/08 00:29

 分别以头插法和尾插法建立两个数据域定义为整型的升序单链表,再将这两个有序链表合并成一个新的无重复元素的有序链表,最后可以根据输入的数据,先找到相应的结点,后删除之。


#include<stdio.h>#include<stdlib.h>typedef struct node{    int  data;    struct node *next;}node;node * qbuild(node *first)     //头插法{int i,n,a[100];node *s;printf("输入n:");scanf("%d",&n);first=(node*)malloc(sizeof(node));first->next=NULL;for(i=0;i<n;i++){s=(node*)malloc(sizeof(node));printf("输入a[%d]:",i);    scanf("%d",&a[i]);        s->data=a[i];s->next=first->next;first->next=s;}return first;}   node * hbuild(node *first)         //尾插发{int i,n,a[100];struct node *s,*r;printf("输入n:");scanf("%d",&n);first=(node*)malloc(sizeof(node));r=first;for(i=0;i<n;i++){s=(node*)malloc(sizeof(node));        printf("输入a[%d]:",i);    scanf("%d",&a[i]);s->data=a[i];r->next=s;        r=s;}r->next=NULL;return first; } node * hebing(node *La,node *Lb)         // 将两个有序链表合并{node *pa,*pb,*pc,*Lc;pa=La->next;pb=Lb->next;Lc=pc=La;while(pa && pb){if(pa->data < pb->data){pc->next =pa;pc=pa;pa=pa->next ;}else if(pa->data > pb->data){pc->next =pb;pc=pb;pb=pb->next;}    else{            pc->next =pa;pc=pa;pa=pa->next ;pb=pb->next ;}}pc->next =pa?pa:pb;free(Lb);    return Lc;}node * shanchu(node *first,int i)          //删除一个链表中的一个字符{    node *p,*q;p=first->next;while(p)    {if((p->next )->data==i){   q=p->next  ;   p->next =q->next;   free(q);   break;}   p=p->next;}return first;}void display(node *first){struct node *p;p=first->next;while(p!=NULL)    {printf("%d ",p->data);p=p->next;}    printf("\n");}int main()                           //主函数{   int m;struct node *a,*b,*c;    a=qbuild(a);    printf("打印链表a:");    display(a);        b=hbuild(b);    printf("打印链表b:");    display(b);       c=hebing(a,b);    printf("打印链表c:");display(c);printf("输入删除的数m:");scanf("%d",&m);c=shanchu(c,m);printf("打印删除后的链表c:");display(c);    return 0;}
输入输出实例;

输入n:5输入a[0]:9输入a[1]:5输入a[2]:4输入a[3]:3输入a[4]:1打印链表a:1 3 4 5 9输入n:5输入a[0]:1输入a[1]:3输入a[2]:4输入a[3]:6输入a[4]:8打印链表b:1 3 4 6 8打印链表c:1 3 4 5 6 8 9输入删除的数m:5打印删除后的链表c:1 3 4 6 8 9--------------------------------Process exited after 32.78 seconds with return value 0请按任意键继续. . .




1 0