
给定一个链表,我们需要删除它的第一个元素并将指针返回到新链表的头部。
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++程序以及我们解决的完整
.........................................................