#include<stdio.h>
#include<stdlib.h>
#define N 9
typedef struct node{
int data;
struct node * next;
}ElemSN;
ElemSN * Createlink(int a[]){ //逆向创建单向链表
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("%2d\n",p->data);
}
}
ElemSN * DelSamenode(ElemSN*h){
ElemSN * p, * q, * Pkey;//p,q指针联动 Pkey哨兵,p指针的值与PKey比较,相等就删除,不相等pq联动
Pkey=h;
while(Pkey){
q=Pkey;
p=Pkey->next;
while(p){
if(Pkey->data!=p->data){ //不等,pq联动
q=p;
p=p->next;
}
else{
q->next=p->next;
free(p); //先释放p,p再后移,否则剩余的链就挂在了p指针后面以释放后面的链就找不到头指针,属于游离状态
p=q->next;
}
}
Pkey=Pkey->next; //Pkey每次后移一位
}
return h;
}
int main(void){
int a[]={2,2,3,4,2,3,3,2,5};
ElemSN * head;
head=Createlink(a,9);
head=DelSamenode(head);
Printlink(head);
}