题目原型:
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 class ReorderList
{
public ListNode reverseList(ListNode head)
{
if (head == null)
return head;
ListNode p, q, t;
p = head;
int len = 0;
// 求得链表长度
while (p != null)
{
len++;
p = p.next;
}
p = head;
q = p;
for (int i = 0; i <= len; i++)
{
if (len % 2 == 1)
{
if (i == len / 2 + 1)
{
break;
}
q = p;
p = p.next;
} else
{
if (i == len / 2)
{
break;
}
q = p;
p = p.next;
}
}
// 半逆置链表
q.next = null;
q = p;
if (p != null)
p = p.next;
if (p != null)
t = p.next;
else
t = null;
if (q != null)
q.next = null;
// System.out.println(q.val);
while (p != null)
{
p.next = q;
q = p;
p = t;
if (t != null)
t = t.next;
}
// 插入
p = head;
if (q != null)
t = q.next;// 此时q指向最后一个节点,也就是半逆置后的第一个节点
while (q != null)
{
q.next = p.next;
p.next = q;
p = q.next;
q = t;
if (t != null)
t = t.next;
else
t = null;
}
return head;
}
public void reorderList(ListNode head)
{
ListNode p;
p = reverseList(head);
while (p != null)
{
System.out.print(p.val + " ");
p = p.next;
}
}
public static void main(String[] args)
{
int N = 4;
int i = 2;
ListNode node;
ListNode pre;
ListNode head;
pre = new ListNode(1);
head = pre;
while (i <= N)
{
node = new ListNode(i);
pre.next = node;
pre = node;
i++;
}
ReorderList r = new ReorderList();
r.reorderList(head);
}
}