我有麻烦创建一个链接列表以相反的顺序从给定的链表。从给定的LinkedList创建一个反向LinkedList在C++
我来自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
你手写的乐趣/学习链表?你知道标准库有一个链表实现吗? – 2011-02-05 17:26:25
我在努力学习。 – Tony 2011-02-05 17:37:33
错误:您将current-> next改为等于“tempHead”,然后尝试使用“current = current-> next”移动到下一个节点。 – MerickOWA 2011-02-05 21:11:08