1. 程式人生 > >連結串列基礎(C語言實現)

連結串列基礎(C語言實現)


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Node{
 int data;
 struct Node *next;

};
//建立帶有頭結點的單向連結串列
struct Node * SList_Creat() {
 int data=0;
 //建立頭結點
 struct Node *head=NULL,*pm=NULL,*pCur=NULL;
 head = (struct Node*)malloc(sizeof(struct Node));
 if (head == NULL) {
  return NULL;
 }
 head->data = 0;
 head->next = NULL;
 //從鍵盤輸入資料,建立業務結點
 printf("please enter the data of node(-1:quit)");
 scanf("%d", &data);
 //迴圈建立
 pCur = head;
 while (data != -1) {
  pm= (struct Node*)malloc(sizeof(struct Node));
  if (pm == NULL) { 
   return NULL;
  }
  pm->data = data;
  pm->next = NULL;
  pCur->next = pm;
  pCur = pCur->next;
  printf("please enter the data of node(-1:quit)");
  scanf("%d", &data);
 }
 return head;
 
}

//列印連結串列
int SLlist_Print(struct Node *head) {
 if (head == NULL) {
  return -1; 
 }
 struct Node *pm = NULL;
 pm = head->next;
 printf("\nBegin ");
 while (pm != NULL) {
  printf("%d ", pm->data);
  pm = pm->next;
 }
 printf("End\n");
}
//在值為x的節點前,插入值為y的值,若值為x的節點不存在,則插在表尾
int SLlist_NodeInsert(struct Node *head, int x, int y) { 
 int i = 1;
 if (head == NULL) {
  return -1;
 }
 struct Node *p1 = NULL,*p2=NULL, *tmp = NULL;
 tmp = (struct Node*)malloc(sizeof(struct Node));
 if (tmp == NULL) {
  return -1;
 }
 tmp->data = y;
 tmp->next = NULL;

 p1 = head;
 p2 = head->next;
 while (p2) {
  if (p2->data == x) {
   break;
  }
   p1 = p1->next;
   p2 = p2->next;
 }
   tmp->next = p2;
   p1->next = tmp;
 return 0;
}

//刪除值為x的結點
int SLlist_NodeDel(struct Node *head, int x) {
 if (head == NULL) {
  return -1;
 }
 struct Node*p1 = NULL, *p2 = NULL;
 p1 = head;
 p2 = head->next;
 while (p2) {
  if (p2->data == x) {
   
   break;
  }
  p1 = p2;
  p2 = p2->next;
   
 }
 if (p2 == NULL) {
  printf("沒有找到要刪除的節點\n");
  return 0;
 }
 p1->next = p2->next;
 free(p2);
 return 0;
}

//銷燬連結串列
int SLlist_Destory(struct Node*head) {
 if (head == NULL) {
  return -1;
 }
 struct Node *p = head,*tmp=NULL;
 while (p) {
  tmp = p->next;
  free(p);
  p = tmp;
 }
}

//連結串列逆置
int SList_Resve(struct Node *head) {
 if (head == NULL) {
  return -1;
 }
 struct Node *p=NULL, *q=NULL, *t=NULL;
 if (head->next == NULL || head->next->next == NULL) {
  return -2;
 }
 p = head->next;
 q = p->next;
 while (q != NULL) {
  //逆置之前把q的後繼節點儲存
  t = q->next;
  //逆置操作
  q->next = p;
  //前驅節點後移
  p = q;
  //逆置結點後移
  q = t; 
 }
 head->next->next = NULL;
 head->next = p;
 return 0;
}


void main() {
 struct Node *head = NULL;
 head = SList_Creat();
 SLlist_Print(head);
 
 SLlist_NodeInsert(head, 20, 19);
 SLlist_Print(head);
 SLlist_NodeDel(head, 20);
 SLlist_Print(head);
 SList_Resve(head);
 SLlist_Print(head);

 //SLlist_Destory(head);
 system("pause");
}