我們已經在以前關于單鏈接串列的文章中討論了“鏈接串列介紹”和“鏈接串列插入”,
讓我們制定問題陳述以了解洗掉程序,給定一個“鍵”,洗掉該鍵在鏈表中的第一個匹配項,
要從鏈接串列中洗掉節點,我們需要執行以下步驟,
1)找到要洗掉的節點的上一個節點,
2)更改上一個節點的下一個節點,
3)待洗掉節點的可用記憶體,
由于鏈表的每個節點都是使用C語言中的malloc()動態分配的,因此我們需要呼叫free()來釋放為要洗掉的節點分配的記憶體,
C ++
#include <bits/stdc++.h> usingnamespacestd; classNode{ public: intdata; Node* next; }; voidpush(Node** head_ref, intnew_data) { Node* new_node = newNode(); new_node->data =https://www.cnblogs.com/258a/p/ new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } voiddeleteNode(Node** head_ref, intkey) { Node* temp = *head_ref; Node* prev = NULL; if(temp != NULL && temp->data =https://www.cnblogs.com/258a/p/= key) { *head_ref = temp->next; delete temp; return; } while(temp != NULL && temp->data != key) { prev = temp; temp = temp->next; } if(temp == NULL) return; prev->next = temp->next; delete temp; } voidprintList(Node* node) { while(node != NULL) { cout << node->data << " "; node = node->next; } } intmain() { Node* head = NULL; push(&head, 7); push(&head, 1); push(&head, 3); push(&head, 2); puts("Created Linked List: "); printList(head); deleteNode(&head, 1); puts("\nLinked List after Deletion of 1: "); printList(head); return 0; }
C語言
#include <stdio.h> #include <stdlib.h> structNode { intdata; structNode *next; }; voidpush(structNode** head_ref, intnew_data) { structNode* new_node = (structNode*) malloc(sizeof(structNode)); new_node->data =https://www.cnblogs.com/258a/p/ new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } voiddeleteNode(structNode **head_ref, intkey) { structNode* temp = *head_ref, *prev; if(temp != NULL && temp->data =https://www.cnblogs.com/258a/p/= key) { *head_ref = temp->next; free(temp); return; } while(temp != NULL && temp->data != key) { prev = temp; temp = temp->next; } if(temp == NULL) return; prev->next = temp->next; free(temp); } voidprintList(structNode *node) { while(node != NULL) { printf(" %d ", node->data); node = node->next; } } int main() { structNode* head = NULL; push(&head, 7); push(&head, 1); push(&head, 3); push(&head, 2); puts("Created Linked List: "); printList(head); deleteNode(&head, 1); puts("\nLinked List after Deletion of 1: "); printList(head); return0; }
輸出:
創建的鏈接串列: 2 3 1 7
洗掉后的鏈接串列: 2 3 7
希望對你有幫助~
另外如果你想更好的提升你的編程能力,學好C語言C++編程!彎道超車,快人一步!筆者這里或許可以幫到你~
C語言C++編程學習交流圈子,QQ群1090842465【點擊進入】微信公眾號:C語言編程學習基地
分享(原始碼、專案實戰視頻、專案筆記,基礎入門教程)
歡迎轉行和學習編程的伙伴,利用更多的資料學習成長比自己琢磨更快哦!
編程學習書籍分享:

編程學習視頻分享:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/233442.html
標籤:其他
上一篇:0080. Remove Duplicates from Sorted Array II (M)
下一篇:手寫玩具 - 快速排序
