题目描述:
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}
.
题目分析:
将一个链表按一定规律反转,着重看其规律:可以看到基本是将链表君分为两部分——前一部分以及后一部分,并将后半部分倒序与前半部分链表交叉连接。
public void reorderList(ListNode head) {
if (head != null && head.next != null && head.next.next != null) {
int count = 0;
ListNode l = head;
while (l != null) {
l = l.next;
count++;
}
int mid = 1;
ListNode midNode = head;
//找到后半部分链表的头结点
while (mid <=count / 2) {
midNode = midNode.next;
mid++;
}
ListNode midNext=midNode.next;
//System.out.println(midNext.val);
midNode.next=null;
//将后半部分链表链表逆转
ListNode h2 = reverseList(midNext);
ListNode h1 = head;
ListNode h3 = h2;
ListNode h4=h1;
//将两部分链表交叉连接
while (h1 != null && h2 != null) {
h4=h1.next;
h1.next = h2;
h3 = h2.next;
h2.next = h4;
h1 = h4;
h2 = h3;
}
}
}
//逆转链表
public ListNode reverseList(ListNode head) {
ListNode p1 = head.next;
head.next=null;
ListNode p2 = p1;
while (p1 != null) {
p2 = p1.next;
p1.next = head;
head = p1;
p1 = p2;
}
p1=head;
while (p1 != null) {
//System.out.println("p1 "+p1.val);
p1 = p1.next;
}
return head;
}