[Leetcode] 143. Reorder List

题目:
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes’ values.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.

思路:遍历得到链表的长度,遍历得到链表的中间位置后的结点,将中间位置后的链表逆序,然后再将逆序的结点依次间隔插入前半段链表中。

java具体实现:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void reorderList(ListNode head) {
       if(head == null){
            return ;
        }
        int len = 0;
        ListNode p = head;
        ListNode end = head;
        while(p != null){
            p = p.next;
            len++;
        }
        if(len % 2 == 1){
            len = len + 1;
        }
        int mid = len/2;
        int i = 0;
        ListNode start = head;

        while(i < mid){
            start = start.next;
            if(i == mid-2){
                end = start;
            }
            i++;
        }
        end.next = null;
        start = rev(start);
        p = head;
        while(start!=null){
            ListNode temp = start;
            start = start.next;
            temp.next = p.next;
            p.next = temp;
            p = p.next.next;
        }


    }

    public ListNode rev(ListNode head){
        if(head == null){
            return head;
        }
        ListNode p1 = head;
        if(p1.next == null){
            return head;
        }
        ListNode p2 = p1.next;
        if(p2.next == null){
            p2.next = p1;
            p1.next = null;
            head = p2;
        }else{
            ListNode p3 = p2.next;
            p1.next = null;
            while(p3!= null){
                p2.next = p1;
                p1 = p2;
                p2 = p3;
                p3 = p3.next;
            }
            p2.next = p1;
            head = p2;
        }
        return head; 
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值