詳解C語言之單鏈表
一、思路步驟
1. 定義結(jié)構(gòu)體
a.數(shù)據(jù)域:用來存放數(shù)據(jù)
b.指針域:用來存放下一個數(shù)據(jù)的位置
2.初始化
申請頭結(jié)點,并將其初始化為空
3.求當(dāng)前數(shù)據(jù)元素的個數(shù)
a.設(shè)置一個指針變量p指向頭結(jié)點和計數(shù)變量size等于0
b.循環(huán)判斷p->next是否為空,如果不為空,就讓指針p指向它的直接后繼結(jié)點,并讓size自增
c.返回size
4.插入
a.設(shè)置兩個指針,一個指向頭結(jié)點,另一個要動態(tài)申請內(nèi)存空間存放要插入的數(shù)
b.找到要插入位置的前一位,并判斷插入位置是否正確
c.生成新結(jié)點,給新結(jié)點數(shù)據(jù)域賦值,執(zhí)行步驟①,在執(zhí)行步驟②
5.刪除
a.設(shè)置兩個指針p、q,p指向頭結(jié)點,q指向要被刪除的結(jié)點
b.找到要刪除位置的前一位,并判斷刪除位置是否正確、存在
c.q指向被刪除的結(jié)點,將被刪除結(jié)點的數(shù)據(jù)域賦值給x,p指向被刪除結(jié)點的下一個結(jié)點,釋放q的內(nèi)存空間
6.釋放內(nèi)存空間
最后記得將頭結(jié)點置空哦!要不然容易出現(xiàn)野指針。
二、代碼
#include <stdio.h> #include <stdlib.h> typedef int DataType;//給int起個別名,方便以后修改 typedef struct Node { DataType data;//數(shù)據(jù)域 struct Node *next;//指針域 }SLNode; //初始化 void ListInit(SLNode **head) { *head = (SLNode *)malloc(sizeof(SLNode));//申請頭結(jié)點 (*head)->next = NULL; } //求當(dāng)前數(shù)據(jù)元素個數(shù) int ListLength(SLNode *head) { SLNode *p = head; int size = 0; while (p->next != NULL) { p = p->next; size++; } return size; } //插入 int ListInsert(SLNode *head, int i, DataType x) { SLNode *p, *q; int j; p = head; j = -1; while (p->next != NULL && j < i - 1) { p = p->next; j++; } if (j != i - 1) { printf("插入?yún)?shù)位置錯誤!??!\n"); return 0; } q = (SLNode *)malloc(sizeof(SLNode));//生成新結(jié)點 q->data = x; q->next = p->next; p->next = q; return 1; } //刪除 int ListDelete(SLNode *head, int i, DataType *x) { SLNode *p, *q; int j; p = head; j = -1; while (p->next != NULL && p->next->next != NULL && j < i - 1) { p = p->next; j++; } if (j != i - 1) { printf("刪除位置參數(shù)錯誤?。?!\n"); return 0; } q = p->next; *x = q->data; p->next = p->next->next; free(q);//釋放被刪除結(jié)點的內(nèi)存空間 return 1; } //按位取 int ListGet(SLNode *head, int i, DataType *x) { SLNode *p; int j; p = head; j = -1; while (p->next != NULL && j < i) { p = p->next; j++; } if (j != i) { printf("取出位置參數(shù)錯誤!??!\n"); return 0; } *x = p->data; return 1; } //釋放 void ListDestroy(SLNode **head) { SLNode *p, *q; p = *head; while (p != NULL) { q = p; p = p->next; free(q); } *head = NULL; } int main() { SLNode *head; int i, x; ListInit(&head); for (i = 0; i < 10; i++) ListInsert(head, i, i + 10); ListDelete(head, 9, &x); for (i = 0; i < ListLength(head); i++) { ListGet(head, i, &x); printf("%d ", x); } ListDestroy(&head); system("pause"); return 0; }
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
C++中main函數(shù)怎樣調(diào)用類內(nèi)函數(shù)
這篇文章主要介紹了C++中main函數(shù)怎樣調(diào)用類內(nèi)函數(shù)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08