简体   繁体   中英

How to reverse a linked list

I was working on Stack Overflow and came up across the #92.

Reverse a linked list 2 question. This is the question's description: Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list. For example, given the linked list [1,2,3,4,5] 1, 4 the list should become [4,2,3,1,5]

It works for all runs but my code produces the wrong answer for one test case, which doesn't make sense. given. [1,2,3,4] 1,4 with 1 being left position an 4 being right position what makes sense for the list to become is [4,2,3,1] which is what my code produces. The correct answer they display is [4,3,2,1] which is screwing with my head and I can't understand why it's doing that. Any heads up are appreciated.

class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) 
    {
        int x = 1;

        ListNode * left_node = nullptr;
        ListNode * right_node = nullptr;
        ListNode * curr = head;
        int temp = 0;
                
        if (!head)
            return nullptr;
        
        while(curr)
        {
            if(x == left)
                left_node = curr;
                
            if(x == right)
                right_node = curr;
            curr = curr->next;
            ++x;
        }
        
        temp = left_node->val;
        left_node->val = right_node->val;
        right_node->val = temp;
     
        return head;
    }

Your solution implements swapping the values for the 2 indexes left and right, which matches the example given in the question.

But the question was to reverse the list between left and right, not just swap the two end points. So 1,2,3,4 becoming 4,3,2,1 is the correct solution and both the example and your solution are wrong, they only swap the entpoints.

PS: Most languages start counting at 0.

@Goswin Von Brederlow has already pointed out what is wrong, I will add a visual representation of what you are doing. Can you spot the problem?

在此处输入图像描述

EDIT: You can look in the comments for a better solution in terms of time and space (and also for a worse one).

After the while you should traverse the linked list. Since you don't have a "prev" (no double linked list) you need to traverse it multiple times to reverse it. I prepared a visualization of the algo, which uses a copy from left to right. And a support node for the prev node at each iteration. It uses idx and oidx to keep track of the position in the original and copied list.

在此处输入图像描述

And here are the steps of the iteration:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM