将链表的所有其他元素(就地)转移到java中的链表的末尾

时间:2014-01-30 19:00:10

标签: java algorithm linked-list singly-linked-list

问题如下: 给定linked list后,将候补indices移至list

后面

代表:

input:         :  [0] -> [1] -> [2] -> [3] -> [4] -> [5] -> [6] -> [7]
expected output:  [0] -> [2] -> [4] -> [6] -> [1] -> [3] -> [5] -> [7] /

从预期输出中可以看出,奇数位置(索引)处的元素被移动到linkedlist的后面。我试图实现这一点;我可以删除奇数索引,但它们没有链接到列表的末尾。

我的代码在这里:

public void shift(){
    if (front==null) return;

    ListNode curr=front;
    ListNode temp=curr.next;
    while (curr.next!=null && curr.next.next!=null){
        curr.next=curr.next.next;
        curr=curr.next;
        temp.next=curr.next;
     }
     curr.next=temp;
    temp.next=null;
}


expected output: front -> [0] -> [2] -> [4] -> [6] -> [1] -> [3] -> [5] -> [7] /
my output: front -> [0] -> [2] -> [4] -> [6] -> [1] /

我需要一些帮助

P.S:否则必须使用辅助存储器。没有其他的包含!!!所以这是一个就地重新安排

4 个答案:

答案 0 :(得分:2)

使用奇数索引处的元素和具有偶数索引处的元素的另一列表形成列表。将奇数列表附加到偶数列表。时间复杂度为O(n),辅助空间复杂度为O(1)。

    public void shift() {
       if (front == null)
            return;
        ListNode oddList, even, odd;
        oddList = even = odd = front;
        oddList = front.next;
        while (even.next != null) {
            odd.next = even.next;
            odd = even.next;
            even.next = odd.next;
            if(odd.next != null) {
                even = odd.next;
                odd.next = null;
            } else {
                odd.next = null;
                break;
            }
        }
        if(oddList != null) {
            even.next = oddList;
        }
        //"front" points to the start of the new list.
   }

答案 1 :(得分:0)

您需要存储对列表背面的引用。然后,遍历列表,并将所有其他元素添加到结尾。

public void shift() {
    if (front == null)
        return;

    ListNode curr = front;
    ListNode temp;
    ListNode back = front;
    while (back.next != null)
        back = back.next;
    ListNode originalBack = back;

    while (curr.next != originalBack){
        temp = curr.next;
        curr.next = curr.next.next;
        temp.next = null;
        back = back.next = temp;
        curr = curr.next;
    }
}

答案 2 :(得分:0)

在遍历时,弹出所有其他项目,并将它们链接在一起以制作第二个列表。当您到达第一个列表的末尾时,请附加第二个列表。我在我的ipad上,所以我无法编码,但一旦上线就会发布。

答案 3 :(得分:0)

可以通过这种方式完成我的朋友,希望这可以帮助你

public void shift(){
    if (front==null) return;

    ListNode curr=front;
    ListNode temp=curr.next;
    while (curr.next!=null){
        curr.next=curr.next.next;
        curr=curr.next;

     }
     curr.next=temp;

}




after 1st pass 0->2, 
after 2nd pass 1->3,
after 3rd pass 2->4, 
after 4th pass 3->5,
after 5th pass 4->6, 
after 6th pass 5->7,

and then 7->next is null so we assign tmp to it which is pointing to 1.