使用值反转双向链接列表

时间:2017-09-24 19:43:44

标签: c++ reverse doubly-linked-list

我目前无法获得双向链接列表的反向功能以正确地为作业工作,我已经阅读了其他主题并在谷歌上进行了搜索但通常不同之处在于我的问题通过了常量并返回" dlist"。教授提供了一个代码测试员"它表示我的代码在执行"反向(反向(dlist c))"它不等于它本身就是" c"。 [反转它两次不等于自己]。

dlist类是:

class dlist {
public:
dlist() { }
int sizeOfDlist =0; // To keep track of size 
struct node {
    int value;
    node* next;
    node* prev;
};

node* head() const { return _head; } // _head = beginning of list
node* tail() const { return _tail; } // _tails = end of list
node* _head = nullptr;
node* _tail = nullptr;

这里有相反的功能:

dlist reverse(const dlist& l){
if(l._head == nullptr||l._tail ==nullptr){ // Checks if l list is empty
    dlist newRList;
    return newRList;//return a blank list;
}

if(l.head()!=nullptr){
    dlist::node* temp;
    dlist::node* ptr1 = l._head;
    dlist::node* previous = nullptr;

    while(ptr1 != nullptr){
        temp = ptr1->next;
        ptr1->next = previous;
        previous = ptr1;
        ptr1 = temp;
    }
    dlist newRList;
    newRList._head = previous;
    return newRList;
   }
else //if something passes by, return original list
    return l;
}

每个dlist节点都有一个指向前一个节点的指针和一个指向下一个节点的指针。 dlist节点还包含int值。

我试图实现的是创建一个从原始列表开始的列表" tail"或结束。然后该列表将倒退并交换" next"和" prev"它随之而来的指针。我做错了什么?

已解决:通过使用push_front函数将值添加到列表的前面并推送其后的所有其他内容,我能够从给定的常量dlist中获取值,并且push_front all将价值观转化为" newRList"这颠倒了订单。

感谢用户4581301和Basya Perlman帮助我,这里有新的反向功能:

dlist reverse(const dlist& l){
if(l._head == nullptr||l._tail ==nullptr){ // Checks if l list is empty
    dlist newRList;
    return newRList;//return a blank list;
}

if(l.head()!=nullptr){
   dlist newRList;
   for(int n=0; n<l.size(); n++){ // Size function checks the size of the doubly linked list 

       newRList.push_front(l.valueGetter(n)); // Value Getter is a function that grabs the value at a specific [iteration], push_front pushes said value into the front of the list.
    }
    return newRList;
}
else //if something passes by, return original list 
    return l;
}

1 个答案:

答案 0 :(得分:0)

您的反向功能看起来像是设置为返回新的dlist。它返回一个对象,而不是指针或引用。

此外,您的参数是const dlist,但您尝试将其反转,然后将新指针指向列表的头部并返回该参数。然后测试人员将返回的列表与原始列表进行比较;但原始列表,原本是const,但是被修改了?我有点困惑,所以也许运行你的程序的计算机也是: - )

从函数定义中,看起来好像是通过以相反的顺序将元素复制到新列表中来创建新列表,并保持原始列表不变。在您的评论中,您有一个push_back和一个push_front函数;您可以循环遍历现有列表并将每个元素的副本推送到新列表中,以反转它(无论您是否需要显式复制,都取决于我没有的push_front函数的定义)。