循環鏈表的key刪除

#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,*t;

 for(i=0;i<N;i++){

p=(ElemSN*)malloc(sizeof(ElemSN));

         p->data=a[i];

if(!h)

h=t=p;

else

p->next=h;

t=t->next=p;

 }

   return h;

}//建立循環鏈表

ElemSN*DelKeyNode(ElemSN*h,int key){

      ElemSN*p,*q;

      p=h;

      q=NULL;

      do{

      if(p->data-key) {//遍歷的結點的data與key不相等

  q=p;

          p=p->next;

      }//指針後移,繼續遍歷

  else break;//相等跳出循環

      }while(p-h);//循環結束:1.p指針只在與key值相等的結點上;2:p指針遍歷完鏈表沒找到,此時p=h;

      if(p==h&&q)

  printf("NO\n");

      else {

  if(p==h){//頭結點data==key,此時需要找到h的上一個結點,

for(q=h;q->next-h;q=q->next);//q在h的上一結點

h=h->next; //h後移

}

 q->next=p->next;//斷鏈

 free(p);

      }

  return h;

}

void Printlink(ElemSN*h){

     ElemSN*p;

     p=h;

     do{

     printf("%2d\n",p->data);

    p=p->next;

     }while(p-h);

}

int main(void){

int a[N]={1,2,3,4,5,6,7,8,9};

int key;

ElemSN*head;

head=Createlink(a,9);

printf("key=");

scanf("%d",&key);

head=DelKeyNode(head,key);

Printlink(head);

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章