中创建一个反向LinkedList

中创建一个反向LinkedList

本文介绍了从给定的LinkedList在C ++中创建一个反向LinkedList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我来自一个java背景,刚刚开始做一些C ++。 / p>

你可以查看我的代码,看看有什么问题吗?

  //这是一个linkedlist类的方法,它创建一个反向linkedlist 
//并打印它

void LinkedList :: reversedLinkedList()
{
Node * revHead;

//检查常规列表是否为空
if(head == NULL)
return;

//否则开始反转
node * current = head;
while(current!= NULL)
{
//检查是否是第一个添加的
if(revHead == NULL)
revHead = current;

else
{
//刚刚在开头插入
Node * tempHead = revHead;
current-> next = tempHead;
revHead = current;
}
current = current-> next;

} // end while

//现在打印它
cout< Reversed LinkedList:< endl;

Node * temp = revHead;
while(temp!= NULL)
{
cout< temp-> firstName<< endl;
cout<< temp-> lastName<< endl;
cout<< endl;

temp = temp-> next;
}

} //结束方法


解决方案

更容易:浏览您的链接列表,保存上一个和下一个节点,并让当前节点指向上一个节点:

  void LinkedList :: reversedLinkedList()
{
if(head == NULL)return;

节点* prev = NULL,* current = NULL,* next = NULL;
current = head;
while(current!= NULL){
next = current-> next;
current-> next = prev;
prev = current;
current = next;
}
//现在让头点在最后一个节点(prev)
head = prev;
}


I'm having some trouble create a linkedlist in reverse order from a given linkedlist.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:30