链表 (删除特定元素)

 
 
#include <stdio.h> #include <stdlib.h> typedef struct node { int date; struct node *next; } lnode; void creatlist(lnode *h,int n) { lnode *p,*r; r=h; int i,x; for(i=0; i<n; i++) { scanf("%d",&x); p=(lnode *)malloc(sizeof(lnode)); p->date=x; r->next=p; r=p; } r->next=NULL; } void delet(lnode*h,int x) { lnode *pre,*p; p=h->next; pre=h; while(p!=NULL) { if(p->date==x) { pre->next=p->next; p=p->next; } else { pre=pre->next; p=p->next; } } } void output(lnode *h) { lnode*p; p=h->next; while(p!=NULL) { printf("%d ",p->date); p=p->next; } printf("\n"); } int main() { int n,x; lnode *h; h=(lnode*)malloc(sizeof(lnode)); h->next=NULL; while(scanf("%d",&n)!=-1) { creatlist(h,n); scanf("%d",&x); delet(h,x); output(h); } return 0; }
解法二 #include <stdio.h> #include <stdlib.h> typedef struct node { int date; struct node *next; }lnode; void creatlist(lnode *h,int n) { lnode *p,*r; int x; int i; r=h; for(i=0;i<n;i++) { scanf("%d",&x); p=(lnode*)malloc(sizeof(lnode)); p->date=x; r->next=p; r=p; }r->next=NULL; } void output(lnode *h) { lnode *p; p=h->next; while(p!=NULL) { printf("%d ",p->date); p=p->next; } } void delete1(lnode *h,int x) { lnode *pre,*p,*q; pre=h; p=pre->next; while(p!=NULL) { if(p->date==x) { q=p; pre->next=p->next; free(q); p=p->next; } else { pre=p; p=p->next; } } } int main() { int n,x; lnode *h; while(scanf("%d",&n)!=-1) { h=(lnode*)malloc(sizeof(lnode));h->next=NULL; creatlist(h,n); scanf("%d",&x); delete1(h,x); output(h); printf("\n"); } return 0; }

猜你喜欢

转载自blog.csdn.net/xqx1343002589/article/details/80413519