从给定的LinkedList在C++中创建反向LinkedList

Ton*_*ony 4 c++ linked-list

我在从给定的链表中以相反的顺序创建链表时遇到了一些麻烦.

我来自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
Run Code Online (Sandbox Code Playgroud)

Xeo*_*Xeo 47

更简单的一个:浏览链接列表,保存上一个节点和下一个节点,然后让当前节点指向前一个节点:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • @user:不是来自OP中的代码.`Node`是一个内部类型,`reversedLinkedList`就地反转列表. (2认同)