給定一個(gè)鏈表,我們需要?jiǎng)h除它的第一個(gè)元素并將指針返回到新鏈表的頭部。
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
登錄后復(fù)制
在給定的問題中,我們需要?jiǎng)h除列表的第一個(gè)節(jié)點(diǎn),并將頭移動(dòng)到第二個(gè)元素并返回頭。
找到解決方案的方法
在這個(gè)問題中,我們可以將頭移動(dòng)到下一個(gè)位置,然后釋放前一個(gè)節(jié)點(diǎn)。
示例
#include <iostream> using namespace std; /* Link list node */ struct Node { int data; struct Node* next; }; void push(struct Node** head_ref, int new_data) { // pushing the data into the list 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; // temp becomes head head = head -> next; // our head becomes the next element delete temp; // we delete temp i.e. the first element for (temp = head; temp != NULL; temp = temp->next) // printing the list cout << temp->data << " "; return 0; }
登錄后復(fù)制
輸出
23 11 29 12
登錄后復(fù)制
上述代碼說明
我們只需要將頭移動(dòng)到程序中的下一個(gè)元素,然后刪除前一個(gè)元素,然后打印新列表即可。給定程序的總體時(shí)間復(fù)雜度為 O(1),這意味著我們的程序不依賴于給定的輸入,這是我們可以實(shí)現(xiàn)的最佳復(fù)雜度。
結(jié)論
在這篇文章中,我們解決了一個(gè)刪除鏈表第一個(gè)節(jié)點(diǎn)的問題。我們還學(xué)習(xí)了這個(gè)問題的C++程序以及我們解決的完整方法。我們可以用其他語言比如C、java、python等語言來編寫同樣的程序。我們希望這篇文章對(duì)您有所幫助。
以上就是使用C++刪除鏈表的第一個(gè)節(jié)點(diǎn)的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注www.xfxf.net其它相關(guān)文章!