單鏈表的基本操作(代碼優化)

#include


typedef struct node {
   int data;
   struct node * next;
}linknode;


linknode * initlink(){                                                          //初始單鏈表
   linknode * head = (linknode *)malloc(sizeof(linknode));
   head->next=NULL;
   return head;
}


int adddata(linknode * head,int arr[] ,int n) {           //表尾增加數據
   int i;
   linknode * p1=NULL;
   linknode * p2=NULL;
   if(head==NULL) {
      head=initlink();
      p1=head;
   }
   else {
      p1=head;
      while(p1->next) {
          p1=p1->next;
      }
   }
   for(i=0;i<n;++i) {
     p2=(linknode *)malloc(sizeof(linknode));
     p2->data=arr[i];
     p1->next=p2;
     p1=p2;
   }
   p2->next=NULL;
   return 1;
}


void print(linknode * head) {             //打印數據
  linknode * p=NULL;
  if(head->next==NULL) {
     printf("empty linklist!");
  }
  p=head->next;
  while(p) {
     printf("%d\t",p->data);
     p=p->next;
  }
  printf("\n");
}




int delete(linknode * head,int value) {    //刪除數據
    linknode * p1=NULL;
    linknode *p2=NULL;
    if(head->next==NULL) {
        return -1;
    }
    p1=head;
    p2=p1->next;
    while (p2 && p2->data!=value) {
       p1=p2;
       p2=p2->next;
    }
    if(p2){
      p1->next=p2->next;
      free(p2);
      return 1;
    }
    else 
        return -2;
 }


int length(linknode *head) {    //單鏈表數據長度
int size=0;
linknode * p=head;
if(head->next==NULL) {
        size=0;
    }
while(p->next) {
  size++;
  p=p->next;
 }
 return size;
}


int reverselist(linknode *head){  //單鏈表的逆置
   int size=0;
   size=length(head);
   linknode * p=NULL;
   linknode * q=NULL;
   if(size>1) {
     p=head->next;
     head->next=NULL;
     while(p) {
       q=p->next;
       p->next=head->next;
       head->next=p;
       p=q;
     }
   } 
   return 1;
}
int main(void) {
    int arr[]={1,2,3,4,12};
    int i;
    linknode * head=initlink();
    adddata(head,arr,5);
    print(head);
    i=delete(head,12);
    if(i==1) {
      print(head);
      printf("%d\n",length(head));
      reverselist(head);
      print(head);
    }
    else
      printf("delete failed!\n");
    return 1;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章