gpt4 book ai didi

c++ - 从给定的链表在 C++ 中创建反向链表

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:52:26 24 4
gpt4 key购买 nike

我在从给定链表反向创建链表时遇到了一些问题。

我有 Java 背景,刚开始接触 C++。

你能检查一下我的代码,看看有什么问题吗?我猜我只是在操纵指针,并没有创造任何新东西。

//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

最佳答案

更简单的方法:遍历你的链表,保存上一个和下一个节点,让当前节点指向前一个节点:

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;
}

关于c++ - 从给定的链表在 C++ 中创建反向链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4908193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com