您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2024/4/2 12:07:18发布24次查看
给定一个链表,我们需要删除它的第一个元素并将指针返回到新链表的头部。
input : 1 -> 2 -> 3 -> 4 -> 5 -> nulloutput : 2 -> 3 -> 4 -> 5 -> nullinput : 2 -> 4 -> 6 -> 8 -> 33 -> 67 -> nulloutput : 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等语言来编写同样的程序。我们希望这篇文章对您有所帮助。以上就是使用c++删除链表的第一个节点的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product