//1、实现单链表的建立及基本运算 #include#include #include typedef int Elemtype; typedef struct Node{ Elemtype data; struct Node *next; }Lnode; Lnode* create(int n){ Lnode *head,*p,*q; int i; head = (Lnode*)malloc(sizeof(Lnode)); head->next=NULL; q=head; for(i=0;i data); q->next=p; p->next=NULL; q=p; } q->next=NULL; return head; } int length(Lnode *L){ Lnode *p; p=L; int size = 0; while(p->next!=NULL) { p=p->next; size++; } return size; } Lnode *get(Lnode *L,int i) { Lnode *p; int j; p=L; j=0; while(p->next!=NULL&&jnext; } if(i==j)return p; else return NULL; } int insert(Lnode *L,int i,Elemtype x) { Lnode *p,*q; int j=0; j=i-1; p=get(L,j); if(p==NULL){ printf("Insertion location invalidn"); return 0;} else { q=(Lnode*)malloc(sizeof(Lnode)); q->data=x; q->next=p->next; p->next=q; } return 1; } Lnode *locate(Lnode *L,Elemtype x)//寻找值为x的元素,返回其指针 { Lnode *p; p=L->next; while(p!=NULL) if(p->data==x)break; else p=p->next; return p; } void display(Lnode* L){ Lnode *p; p=L->next; while(p){ printf("%dt",p->data); p=p->next; } printf("n"); } Lnode *deleteElem(Lnode *L,Elemtype x){ if(L->next==NULL)return L; Lnode *p,*q,*t; int i=0; p=L->next,q=L; while(p){ if(p->data==x){ q->next=p->next; free(p); p=q->next; continue; } p=p->next; q=q->next; } return L; } Lnode *merge(Lnode *La,Lnode *Lb,Lnode *Lc){ Lc=create(0); Lnode *a,*b,*c,*cur; a=La->next; b=Lb->next; c=Lc; while(a!=NULL&&b!=NULL) { cur=(Lnode*)malloc(sizeof(Lnode)); if(a->data data){ cur->data=a->data; a=a->next; }else{ cur->data=b->data; b=b->next; } cur->next=c->next; c->next=cur; c=cur; } if(a==NULL){ c->next=b; }else{ c->next=a; } display(Lc); return Lc; } int main(){ Lnode *L,*La,*Lb,*Lc; int num=0; int mark,size; Elemtype a,x; printf("Please input the num of elementsn"); scanf("%d",&num); printf("Please input the elements to establish a linked listn"); L=create(num); printf("The list stored in linked form isn"); display(L); printf("Please input the location and element to be insertedn"); scanf("%d%d",&mark,&x); insert(L, mark, x); display(L); size=length(L); printf("The size of the linked list is %dn",size); printf("Please input the element to be deletedn"); scanf("%d",&a); deleteElem(L,a); display(L); printf("Please input 2 ordered listn"); La=create(num); Lb=create(num); Lc=merge(La,Lb,Lc); }
截图
//2、双向链表 #include#include #define ElemType int typedef struct Dnode{ ElemType data; struct Dnode *prior; struct Dnode *next; }Dnode; Dnode * createDouble(int n)//创建双向链表 { Dnode *head,*p,*q; int i; head=(Dnode *)malloc(sizeof(Dnode)); head->prior=NULL; head->next=NULL; q=head; for (i=0;i next; while (p!=NULL) { printf("%dt",p->data); p=p->next; } printf("n"); return; } int main()//主函数 { int num; Dnode *L; printf("Please input the num of elementsn"); scanf("%d",&num); printf("Please input the elements to establish a double linked listn"); L=createDouble(num); displayDouble(L); }



