Reverse a LinkedList c++ [duplicate]

混江龙づ霸主 提交于 2019-12-02 01:13:48

Since you said you wanted to find the problem on your own, I'll just give you a hint instead of the solution.

Your reverse function works in that it successfully reverses the list. That isn't the problem. You probably have 2 calls to print. One before and one after the reverse. What do you note about the nodes being passed to print in both cases? What does that tell you?

EDIT:

Since you said you've found the problem, I'll post the actual solution.

In your reverse code, you never update the _head of the list, but when you reverse the list, the head does actually change from 4 to 1. Since you never update _head, when you call print the second time (after the reverse call) you start printing at 1, That being the end of the list, that's the only node printed.

The solution is to update _head when you reverse the list. The simplest way to do this is to simply update it in each iteration. This may be slightly less efficient than other possible solutions, but it doesn't change the time complexity of the algorithm -- it's still O(n):

void LinkedList::reverseList()
{
    Node *next=_head;
    Node *prev=0;
    while(next!=0)
    {
        Node *tmp=next->_next;
        next->_next=prev;
        _head = next;
        prev=next;
        next=tmp;
    }
}

Try something like this.

Doubly-linked list:

for (Node * n = _head, * next; ; n = next)
{
    next = n->next;

    std::swap(n->next, n->prev);

    if (next == NULL) { _head = n; break; }
}

Singly-linked list:

for (Node * n = _head, * prev = NULL, * next; ; prev = n, n = next)
{
    next = n->next;

    n->next = prev;

    if (next == NULL) { _head = n; break; }
}

I like recursion; It's easier to grasp and verify;

Node* LinkedList::reverseList() { // returns tail
  if (!_head || !_head->_next)
      return _head;
  Node* const h = _head;
  _head = _head->_next;
  h->_next = NULL;
  return reverseList()->_next = h;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!