Create a reverse LinkedList in C++ from a given LinkedList(从给定的 LinkedList 在 C++ 中创建一个反向 LinkedList)
问题描述
我在从给定的链表以相反的顺序创建链表时遇到了一些问题.
I'm having some trouble create a linkedlist in reverse order from a given linkedlist.
我有 Java 背景,刚开始做一些 C++.
I come from a java background, and just started doing some C++.
你能看看我的代码,看看有什么问题吗?我猜我只是在操纵指针而不是创建任何新东西.
Can you check out my code and see what's wrong? I'm guessing I'm just manipulating pointer and not creating anything new.
//this is a method of linkedlist class, it creates a reverse linkedlist
//and prints it
void LinkedList::reversedLinkedList()
{
Node* revHead;
//check if the regular list is empty
if(head == NULL)
return;
//else start reversing
Node* current = head;
while(current != NULL)
{
//check if it's the first one being added
if(revHead == NULL)
revHead = current;
else
{
//just insert at the beginning
Node* tempHead = revHead;
current->next = tempHead;
revHead = current;
}
current = current->next;
}//end while
//now print it
cout << "Reversed LinkedList: " << endl;
Node* temp = revHead;
while(temp != NULL)
{
cout << temp->firstName << endl;
cout << temp->lastName << endl;
cout << endl;
temp = temp->next;
}
}//end method
推荐答案
更简单的一个:遍历你的链表,保存上一个和下一个节点,让当前节点指向上一个:
Easier one: Go through your linked list, save the previous and the next node and just let the current node point at the previous one:
void LinkedList::reversedLinkedList()
{
if(head == NULL) return;
Node *prev = NULL, *current = NULL, *next = NULL;
current = head;
while(current != NULL){
next = current->next;
current->next = prev;
prev = current;
current = next;
}
// now let the head point at the last node (prev)
head = prev;
}
这篇关于从给定的 LinkedList 在 C++ 中创建一个反向 LinkedList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从给定的 LinkedList 在 C++ 中创建一个反向 LinkedList
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 从python回调到c++的选项 2022-11-16
- C++ 协变模板 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 近似搜索的工作原理 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01