LintCode:重排链表

描述

给定一个单链表L: L0L1→…→Ln-1Ln,

重新排列后为:L0LnL1Ln-1L2Ln-2→…

必须在不改变节点值的情况下进行原地操作。

样例

给出链表 1->2->3->4->null,重新排列后为1->4->2->3->null

挑战

Can you do this in-place without altering the nodes' values?


思路: 首先我们可以想到,可以将链表倒置一下,用linkedlist2代替,

             那么很容易我们就可以达到我们的结果,第一个节点使用第一个链表的,第二个节点使用第二链表的,依次循环下去,

             直到新链表长度跟原链表一样就可以了。

             但是,我们不可以直接将原链表倒置,这样原链表就没了,所以我们先用快慢指针找到中间节点,然后将中间节点后面的

              元素倒置,然后重复上述的过程就可以达到目的了。


Java实现代码如下:

public class reorderList {
    public static void reorderList(ListNode head) {
        // write your code here
        if(head==null || head.next == null){
            return;
        }
        ListNode middle = findMiddle(head);
        ListNode end = reverse(middle);

        ListNode h = head;
        ListNode node1 = null;
        ListNode node2 = null;
        while (h!=null && end!=null){
            node1 = h.next;
            if(node1==middle){
                node1 = null;
            }
            node2 = end.next;
            h.next = end;
            if(node1!=null){
                end.next = node1;
                end = node2;
            }
            h = node1;
        }
    }

    public static ListNode reverse(ListNode middle){
        ListNode pre = null;
        ListNode work = middle;
        ListNode next = middle.next;
        while (next!=null){
            work.next = pre;
            pre = work;
            work = next;
            next = work.next;
        }
        work.next = pre;
        return work;
    }

    public static ListNode findMiddle(ListNode head){
        ListNode h = head;
        while (h!=null && h.next!=null){
            h = h.next.next;
            head = head.next;
        }
        return head;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值