我有麻煩創建一個鏈接列表以相反的順序從給定的鏈表。從給定的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