方法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;
}
}
}
}
总结:
- 无