Leetcode: Reorder List

url :

https://leetcode.com/problems/reorder-list/description/

描述

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}.

代码

class Solution {
        public void reorderList(ListNode head) {
            if(head == null) return;
            ListNode p = head;
            int count = 0;
            while(p!=null){
                p=p.next;
                count++;
            }

            ListNode[] points = new ListNode[count];
            p = head;
            count = 0;
            while(p!=null){
                points[count++] = p;
                p=p.next;
            }

            int i = 0, j = count-1;
            while(i < j) {
                points[i].next = points[j];
                points[j--].next = points[++i];
            }
            points[i].next = null;
        }
    }

上面的方法总是感觉有点不正宗,下面给出链表的操作,大概就是把链表的后半段作为单独的一段链表,并进行反转,然后在把两个合成一个就行啦,代码如下:

public void reorderList3(ListNode head) {
            if(head==null) return;
            ListNode fast = head, slow = head;
            while(fast!=null && fast.next!=null){
                fast = fast.next.next;
                if(fast!=null){
                    slow = slow.next;
                }
            }
            ListNode pre = null;
            ListNode p = slow.next;
            ListNode post = p==null ? null : p.next;
            while(post!=null){
                p.next = pre;
                pre = p;
                p=post;
                post = post.next;
            }
            if(p!=null)
                p.next = pre;

            slow.next = null;
            ListNode h1 = head;
            ListNode h2 = head.next;
            ListNode m = p;
            while(h1!=null && m!=null) {
                h1.next = m;
                m = m.next;
                h1 = h1.next;
                h1.next = h2;
                h2 = h2 == null? null : h2.next;
                h1 = h1.next;
            }

        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值