您好,登錄后才能下訂單哦!
這篇文章主要介紹了C語(yǔ)言如何編寫(xiě)一個(gè)鏈表,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
本文實(shí)例為大家分享了C語(yǔ)言編寫(xiě)一個(gè)鏈表的具體代碼,具體內(nèi)容如下
1.創(chuàng)建頭鏈表
struct Node* Creatlist(){//創(chuàng)建鏈表頭 struct Node *headnode = (struct Node*)malloc(sizeof(struct Node));//創(chuàng)建動(dòng)態(tài)內(nèi)存鏈表,指針變量 headnode->next = NULL;//鏈表初始化 return headnode; }
2.創(chuàng)建節(jié)點(diǎn)
struct Node* Creatnode(int num){//創(chuàng)建結(jié)點(diǎn),鏈表,參數(shù)數(shù)字域 struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));//創(chuàng)建動(dòng)態(tài)內(nèi)存鏈表,指針變量 newnode->num = num; newnode->next = NULL;//鏈表初始化 return newnode; }
3.插入節(jié)點(diǎn)
void Insetlist(struct Node* list, int num){//頭插法 struct Node* insetnode = Creatnode(num); if (list != NULL){ insetnode->next = list->next; list->next = insetnode; } else{ printf("節(jié)點(diǎn)不存在\n"); } } void Insetlists(struct Node* headnode, int n, int num){//在n節(jié)點(diǎn)處插入,參數(shù)頭節(jié)點(diǎn),在第n個(gè)節(jié)點(diǎn)處插,插入的數(shù)據(jù)num int i = 1; struct Node *t = headnode; while (i < n&& t!= NULL){ t = t->next; i++; } if (t != NULL){ struct Node* insetnode = Creatnode(num); insetnode->next = t->next; t->next = insetnode; } else{ printf("節(jié)點(diǎn)不存在\n"); } }
4.修改節(jié)點(diǎn)
void Modifynode(struct Node* headnode, int n){//修改節(jié)點(diǎn),參數(shù)鏈表,修改的第n個(gè)節(jié)點(diǎn) struct Node* list = headnode; int i = 0; while (i < n&&list != NULL){ list = list->next; i++; } if (list != NULL){ printf("請(qǐng)輸入你要修改的值\n"); int j = 0; scanf("%d", &j); list->num = j; } else{ printf("節(jié)點(diǎn)不存在\n"); } }
5.刪除節(jié)點(diǎn)
定義兩個(gè)指針,一個(gè)指向刪除節(jié)點(diǎn)的上一個(gè)節(jié)點(diǎn),一個(gè)指向要?jiǎng)h除的節(jié)點(diǎn)
void Deletnode(struct Node* headnode, int n){//刪除第n個(gè)節(jié)點(diǎn), int i = 1; struct Node *strat = headnode; struct Node *end = headnode->next; while (i < n&&end != NULL){ strat = strat->next; end = end->next; i++; } if (end != NULL){ strat->next = end->next; free(end); } else{ printf("節(jié)點(diǎn)不存在\n"); } }
6.打印節(jié)點(diǎn)
void Printnode(struct Node* headnode){//打印節(jié)點(diǎn) struct Node* list = headnode; while ((list->next) != NULL){ list = list->next; printf("%d\t", list->num); } printf("\n"); }
7.主函數(shù)
int main(){ struct Node* list = Creatlist(); Insetlists(list, 1, 1); Printnode(list); int i = 0; printf("請(qǐng)輸入修改哪個(gè)節(jié)點(diǎn)\n"); scanf("%d", &i); Modifynode(list, i); Printnode(list); printf("請(qǐng)輸入刪除哪個(gè)節(jié)點(diǎn)\n"); int n = 0; scanf("%d", &n); Deletnode(list, n); Printnode(list); system("pause"); return 0; }
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“C語(yǔ)言如何編寫(xiě)一個(gè)鏈表”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。