鏈表結點的刪除(有重復)
阿新 • • 發佈:2018-08-03
逆向 \n fine turn type sizeof eat create else #include<stdio.h>
#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)
pintf("%2d\n",p->data);
}
ElemSN * DelSamenode(ElemSN*h,int key){
ElemSN * p,* q;
p=h;
while(p){ //p不為空
if(p->data!=key) { //未找到key
q=p; //兩指針聯動
p=p->next;
}
else{ //key找到p指針指著key
if(p!=h){ //判斷是否為頭結點 不是頭結點
q->next=p->next;
free(p);
p=q->next;
}
else{ //是頭結點
h=h->next;
free(p);
p=h;
}
}
}
return h;
}
int main(void){
int a[]={3,2,9,8,9,7,9,6,1};
int key;
ElemSN * head;
head=Createlink(a,9);
printf("key=");
scanf("%2d",&key);
head=DelSamenode(head,key);
Printlink(head);
}
鏈表結點的刪除(有重復)