给定一个链表,我们需要删除它的第一个元素并将指针返回到新链表的头部。
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++删除链表的第一个节点的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号