Results 1 to 2 of 2
  1. #1
    hughng92 is offline Member
    Join Date
    Apr 2017
    Posts
    1
    Rep Power
    0

    Default Split a linked list into two in such a fashion

    I am trying to split a singly linked list called "unsorted" into two lists left and right in such fashion that the odd nodes in "unsorted" will go to left and the even ones will go to right. After that, I want to delete those nodes in "unsorted", and I now have two separate lists: left and right.
    Java Code:
    if(unsorted == null)
        {
            return unsorted;
        }
        else {
            Node temp = unsorted.next.next;
            Node left = unsorted;
            Node right = unsorted.next;
            left.next = null;
            right.next = null;
            unsorted = temp;
            while (temp.next != null) {
                left.next = temp;
                right.next = temp.next;
                left.next.next = null;
                right.next.next = null;
                temp = temp.next.next;
                unsorted = temp;
            }
        }
    I think I am stuck at my logics in the while loop. Before the while loop, I extract the first two nodes in the unsorted list and then delete them. The first the time the loop runs, I can extract the next two nodes in the unsorted list. But for the second time run, is left.next still pointing at the third node in the unsorted list? (Well, I already deleted the first two nodes but for the sake of my description, I need to say the third node so it is easy to describe my logics) If so, I did not successfully update my left and right linked lists, correct? Please give me some hints how to correctly update my left and right lists. Thank you.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: Split a linked list into two in such a fashion

    Last edited by Norm; 04-19-2017 at 02:54 PM.
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. Replies: 0
    Last Post: 09-25-2012, 04:07 AM
  2. Linked List, Array List time complexity
    By Rick99771977 in forum New To Java
    Replies: 4
    Last Post: 08-18-2011, 05:37 AM
  3. Replies: 4
    Last Post: 02-21-2011, 09:34 AM
  4. Linked list inside a linked list
    By viperlasson in forum New To Java
    Replies: 5
    Last Post: 07-26-2010, 11:15 PM
  5. Linked List integer list
    By igniteflow in forum Advanced Java
    Replies: 1
    Last Post: 12-10-2008, 08:53 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •