使用 C++ 删除链表的第一个节点


给定一个链表,我们需要删除其第一个元素并返回新链表的头指针。

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

在给定的问题中,我们需要删除列表的第一个节点,并将我们的头移动到第二个元素并返回头。

寻找解决方案的方法

在这个问题中,我们可以将头移动到下一个位置,然后释放上一个节点。

示例

#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;
}

输出

23 11 29 12

上述代码的解释

在这个程序中,我们只需要将头移动到它的下一个元素,然后删除上一个元素,然后打印新的列表。给定程序的整体时间复杂度为 O(1),这意味着我们的程序不依赖于给定的输入,并且它是我们所能达到的最佳复杂度。

结论

在本文中,我们解决了一个删除链表第一个节点的问题。我们还学习了这个问题的 C++ 程序以及我们解决的完整方法。我们可以用其他语言(如 C、Java、Python 等)编写相同的程序。我们希望您发现本文有所帮助。

更新于: 2021年11月26日

183 次浏览

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.