Leetcode 143. Reorder List

在这里插入图片描述
方法1: recursion。利用一个arraylist先存储所有nodes。时间复杂n,空间复杂n。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    List<ListNode> myList = new ArrayList<>();
    int count = 0;
        
    public void reorderList(ListNode head) {
        if(head == null || head.next == null || head.next.next == null){
            head = head;
        }else{
            ListNode curr = head;
            while(count == 0 && curr != null){
                myList.add(curr);
                curr = curr.next;
            }
            count++;
            ListNode temp = head.next;
            head.next = myList.get(myList.size() -1);
            myList.get(myList.size() -2).next = null;
            myList.remove(0);
            myList.remove(myList.size() - 1);
            reorderList(temp);
            head.next.next = temp;
        }
        
    }
}

方法2: two pointer。感谢上天我终于想到用two pointer来做了。思路很简单,先找到中点,然后reverse后半部分,然后merge前半部分和后半部分。我stuck在merge这个环节花了好长时间。下次回顾的记得看一下。时间复杂n,空间复杂1.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public void reorderList(ListNode head) {
        if(head != null){
            ListNode curr = head;
            ListNode fast = curr;
            ListNode slow = curr;
            while(fast != null && fast.next != null){
                slow = slow.next;
                fast = fast.next.next;
            }

            ListNode copy = slow;
            ListNode prev = null;
            while(copy != null){
                ListNode nextNode= copy.next;
                copy.next = prev;
                prev = copy;
                copy = nextNode;
            }

            ListNode tmp = prev;
            while(tmp.next != null){
                ListNode nextnode = curr.next;
                curr.next = tmp;
                curr = nextnode;

                ListNode nexttmp = tmp.next;
                tmp.next = curr;
                tmp = nexttmp;
            } 
        }  
    }
}

总结:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值