简体   繁体   中英

Reversed Linked List only prints as one node

I was coding on gfg practice to test whether a linked list is a palindrome, and after I reversed the linked list, it showed only one node.

This is the code below (the linked list passed is 1->2->1):-

class Solution
{
    //Function to check whether the list is palindrome.
    boolean isPalindrome(Node head) 
    {
        Node temp=head;
        Node reversed= reverseList(temp);
        Node cur = head;
        
        while(cur!=null)
        {
            System.out.println(cur.data+"    inloop");
            cur=cur.next;
        }
         
        return true;
    } 

    Node reverseList(Node node)
    {        
        Node prev = null;
        Node current = node;
        Node next = null;
        while (current != null) {
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        node = prev;
        return node; 
    }
}

The output of this code is ( the linked list passed is 1->2->1): -

1    inloop

But if I comment out the Node reversed = reverseList(temp); line, the output is as expected: -

1    inloop
2    inloop
1    inloop

Where is my mistake?

When the list is reversed, the previous head of the list has become the tail. Concretely, after that reversal, head references the tail of the now reversed list. A tail has (by definition) a next member that is null , and so your while loop will only iterate once.

Realise that when you reverse the list, you don't have the original order anymore: all next members have lost their original value and now (only) have a reference that reflects the reversed order.

You have a few options to do it right:

  1. Have your reverse method create a new list, so that caller will then have both the original and the reversed list. This will allow you to iterate both lists in tandem and compare the node values as intended

  2. Create an array from the list. Now check whether the array is a palindrome.

  3. The above options need O(n) extra space. You can solve this without O(n) auxiliary space: only reverse half of the list. Here you don't need to create new nodes, but by only reversing half of the list, you can traverse the reversed part and the non-reversed part in tandem and make value comparisons

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