首頁 > 後端開發 > C++ > 使用C++刪除鍊錶的第一個節點

使用C++刪除鍊錶的第一個節點

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
發布: 2023-09-22 09:17:08
轉載
1574 人瀏覽過

使用C++刪除鍊錶的第一個節點

給定一個鍊錶,我們需要刪除它的第一個元素並將指標傳回新鍊錶的頭部。

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;

/* 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;

}

登入後複製

輸出

1

23 11 29 12

登入後複製

上述程式碼說明

我們只需要將頭移到程式中的下一個元素,然後刪除前一個元素,然後列印新清單即可。給定程式的總體時間複雜度為 O(1),這意味著我們的程式不依賴給定的輸入,這是我們可以實現的最佳複雜度。

結論

在這篇文章中,我們解決了一個刪除鍊錶第一個節點的問題。我們也學習了這個問題的C 程式以及我們解決的完整方法。我們可以用其他語言像是C、java、python等語言來寫同樣的程式。我們希望這篇文章對您有幫助。

以上是使用C++刪除鍊錶的第一個節點的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板