鏈表節點的刪除(無重復)
#include<stdlib.h>
#define N 9
typedef struct node{
int data;
struct node * next;
}ElemSN;
ElemSN * Createlink(int a[],int n){ //逆向創建單向鏈表
int i;
ElemSN * h=NULL, * p;
for( i=N-1;i>=0;i--){
p=(ElemSN *)malloc(sizeof(ElemSN));
p->data =a[i];
p->next=h;
h=p;
}
return h;
}
void printlink(ElemSN * h){
ElemSN * p;
for(p=h;p;p=p->next)
printf("%d\n",p->data);
}
ElemSN * Delingkeynode(ElemSN*h,int key) {
ElemSN * p;
ElemSN * q=NULL;
for(p=h;p&&p->data!=key;q=p,p=p->next); //遍歷鏈表,如果找到key指針p不為空,且p指針是q指針的next
if(!p) //key不存在
printf("NO\n");
else {
if(p-h) //key不是頭結點
q->next=p->next; //掛鏈
else
h=h->next; //key是頭指針,頭指針後移
}
free(p); //釋放p指針
return h;
}
int main(void){
int a[]={1,2,3,4,5,6,7,8,9};
int key;
ElemSN * head;
head=Createlink(a,9);
printf("key=");
scanf("%2d",&key);
head=Delingkeynode(head,key);
printlink(head);
}
鏈表節點的刪除(無重復)