
給定一個鍊錶,我們需要刪除它的第一個元素並將指標傳回新鍊錶的頭部。
1 2 3 4 5 | Input : 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Output : 2 -> 3 -> 4 -> 5 -> NULL
Input : 2 -> 4 -> 6 -> 8 -> 33 -> 67 -> NULL
Output : 4 -> 6 -> 8 -> 33 -> 67 -> NULL
|
登入後複製
在給定的問題中,我們需要刪除清單的第一個節點,並將頭移到第二個元素並傳回頭。
找到解決方案的方法
在這個問題中,我們可以將頭移到下一個位置,然後釋放前一個節點。
範例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | # include <iostream>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void push(struct Node** head_ref, int new_data) {
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int main() {
Node* head = NULL;
push(&head, 12);
push(&head, 29);
push(&head, 11);
push(&head, 23);
push(&head, 8);
auto temp = head;
head = head -> next;
delete temp;
for (temp = head; temp != NULL; temp = temp->next)
cout << temp->data << " " ;
return 0;
}
|
登入後複製
輸出
上述程式碼說明
我們只需要將頭移到程式中的下一個元素,然後刪除前一個元素,然後列印新清單即可。給定程式的總體時間複雜度為 O(1),這意味著我們的程式不依賴給定的輸入,這是我們可以實現的最佳複雜度。
結論
在這篇文章中,我們解決了一個刪除鍊錶第一個節點的問題。我們也學習了這個問題的C 程式以及我們解決的完整方法。我們可以用其他語言像是C、java、python等語言來寫同樣的程式。我們希望這篇文章對您有幫助。
以上是使用C++刪除鍊錶的第一個節點的詳細內容。更多資訊請關注PHP中文網其他相關文章!