鏈表的基本操作(元素刪除,插入,鏈表生成,鏈表倒置)
阿新 • • 發佈:2017-06-21
printf 輸出 size ++ can 鏈表的基本操作 nbsp 插入 include
#include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct stu{ int d; struct stu *l; }st; void xj(st *h)//生成單鏈表 { st *l; l=h; int m; scanf("%d",&m); h=(st *)malloc(sizeof(st)); while(m--) { st *s; s=new st; scanf("%d",&s->d); l->l=s; l=s; } l->l=NULL; } void shc(st *h)//輸出鏈表 { h=h->l; while(h->l!=NULL) { printf("%d ",h->d); h=h->l; } printf("%d\n",h->d); } void chr(st *h)//按大小插入元素 { int n; scanf("%d",&n); h=h->l;while(h!=NULL) { if(n<=h->l->d) { st *s; s=new st; s->d=n; s->l=h->l; h->l=s; break; } else h=h->l; } } void shac(st *h)//刪除鏈表第n個元素 { int n; scanf("%d",&n); intk=0; while(h!=NULL) { if(k==n-1) { st *s; s=new st; s=h->l; h->l=h->l->l; free(s);break; } h=h->l; k++; } } void dz(st *h)//倒置鏈表 { st *l; l=new st; l=h->l->l; h->l->l=NULL; while(l!=NULL) { st *s; s=new st; s->d=l->d; s->l=h->l; h->l=s; l=l->l; } } int main() { st *h,*h1; h=new st; h1=new st; h=h1; xj(h); h=h1; shc(h); h=h1; chr(h); h=h1; shc(h); h=h1; shac(h); h=h1; shc(h); h=h1; dz(h); shc(h); return 0; }
鏈表的基本操作(元素刪除,插入,鏈表生成,鏈表倒置)