/**143. Reorder List
* @param head
*/
public void reorderList(ListNode head) {
if (!(head == null || head.next == null)) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
fast = slow.next;
slow.next = null;
if (fast != null && fast.next != null) {
fast = reverse(fast);
}
slow = head;
while (fast != null) {
ListNode tempS = slow.next;
ListNode tempF = fast.next;
slow.next = fast;
fast.next = tempS;
fast = tempF;
slow = tempS;
}
}
}
public ListNode reverse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode p = new ListNode (-1) ;
ListNode phead = p;
p.next = head;
while (head.next != null) {
ListNode temp = p.next;
p.next = head.next;
head.next = head.next.next;
p.next.next = temp;
}
return p.next;
}
//两倍指针的使用
//先找到后一半,然后逆序,最后把前后合并到一起
//计算好slow和fast的位置,slow个数>fast个数
[LeetCode] 143. Reorder List java
最新推荐文章于 2022-01-15 11:02:42 发布