我们有一个单链表,并且我们的任务是从该链表中删除最后一个节点。在这个问题中,我们只需要遍历给定的链表,并简单地删除最后一个节点。
在这种方法中,我们遍历给定的链表,并跟踪前一个节点和当前节点。当我们的当前节点成为最后一个节点时,我们将previous -> next更改为NULL,并删除当前节点。
#include <iostream> using namespace std; struct Node { int data; struct Node* next; }; void push(struct Node** ref, int new_data) { // pushing the node struct Node* new_n = new Node; new_n->data = new_data; new_n->next = (*ref); (*ref) = new_n; } int main() { Node* head = NULL; push(&head, 12); push(&head, 29); push(&head, 11); push(&head, 23); push(&head, 8); auto curr = head, prev = head; if (!curr || !curr -> next) // if list only has one element or the list is empty cout << "Empty\n"; else { while (curr) { // while curr != NULL if (!curr -> next) { prev -> next = NULL; delete(curr); // freeing the space break; } prev = curr; curr = curr -> next; // moving to the next node } } for (Node* temp = head; temp != NULL; temp = temp->next) // printing the data cout << temp->data << " "; return 0; }
8 23 11 29
在这种方法中,我们遍历数组,跟踪当前节点和上一个节点。当当前节点成为最后一个节点时,我们将previous -> next更改为NULL并删除当前节点。给定程序的总体时间复杂度为O(N),其中N是给定列表的大小。
时间复杂度 - O(N)
立即学习“C++免费学习笔记(深入)”;
N:给定数组的大小
在本文中,我们解决了从给定链表中删除最后一个节点的问题。我们还学习了这个问题的C++程序和我们解决的完整方法。我们可以用其他语言编写相同的程序,如C、Java、Python和其他语言。希望您会发现本文有帮助。
以上就是使用C++删除链表的最后一个节点的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号