資料結構 單鏈表實現 純程式碼
阿新 • • 發佈:2019-02-05
單鏈表操作函式原型宣告
node_t *list_init();
//顯示單鏈表
void display(node_t *head);
//在單鏈表上查詢第i個節點的存放地址
node_t *find(node_t *head,int i);
//在單鏈表上第I個節點後面插入值為x的節點
node_t *insert01(node_t *head,datatype x,int i);
node_t *insert02(node_t *head,datatype x,int i);
//在單鏈表上刪除值為x的節點
node_t *delet(node_t *head,datatype x);
單鏈表節點資料結構體
//單鏈表
typedef int datatype;
typedef struct node
{
struct node *next;
//node_t *prev;
datatype data;
}node_t;
完整程式碼
#include "stdio.h" #include <malloc.h> //單鏈表 typedef int datatype; typedef struct node { struct node *next; //node_t *prev; datatype data; }node_t; node_t *list_init(); //顯示單鏈表 void display(node_t *head); //在單鏈表上查詢第i個節點的存放地址 node_t *find(node_t *head,int i); //在單鏈表上第I個節點後面插入值為x的節點 node_t *insert01(node_t *head,datatype x,int i); node_t *insert02(node_t *head,datatype x,int i); //在單鏈表上刪除值為x的節點 node_t *delet(node_t *head,datatype x); node_t *list_init(void) { node_t *head = (node_t *)malloc(sizeof(node_t)); head->next = NULL; head->data = 0; return head; } void display(node_t *head) { int count = 0; node_t *p = head; printf("----- List item -----\n"); while(p != NULL) { printf("%d : [%d]\n",count,p->data); ++count; p = p->next; } } //在單鏈表上查詢第i個節點的存放地址 node_t *find(node_t *head,int i) { node_t *p = head; int index = 1; if(i < 1 ) return NULL; while((p != NULL) && (index++ != i)) { p = p->next; } if(p != NULL) return p; return NULL; } node_t *insert02(node_t *head,datatype x,int i) { node_t *p = head; p = find(head,i); if(p != NULL) { node_t *pnew = (node_t *)malloc(sizeof(node_t)); if(pnew != NULL) { pnew->data = x; pnew->next = p->next; p->next = pnew; } else { printf("malloc error!\n"); } } else { printf("have no the node!\n"); } return head; } //在單鏈表上刪除值為x的節點 node_t *delet(node_t *head,datatype x) { node_t *p = head; node_t *pre = head; while((p != NULL) && (p->data != x)) { pre = p; p = p->next; } if(p != NULL ) { pre->next = p->next; free(p); p = NULL; } return head; } int main(void) { node_t *list_head = list_init(); //insert02(list_head,9,0); insert02(list_head,10,1); insert02(list_head,11,2); insert02(list_head,12,3); insert02(list_head,13,4); insert02(list_head,14,5); insert02(list_head,15,6); display(list_head); delet(list_head,14); delet(list_head,11); printf("after delet 14 11\n"); display(list_head); insert02(list_head,55,2); insert02(list_head,66,5); printf("after insert 55 66\n"); display(list_head); return 0; }
執行結果