给出单链表,L0->L1->L2->L3->......->Ln-1->Ln,
返回更改后的单链表,要求返回的链表是L0->Ln->L1->Ln-1->......->Ln/2->Ln/2+1
要求不能交换链表的数值
做法:首先定位到单链表的中间,并将单链表中间之后的逆置也就是说
LH1: L0->L1->L2->......Ln/2;
LH2: Ln->Ln-1->Ln-2->Ln/2+1;
然后将LH2间隔的插入LH1中
定位到单链表中间的方法比较朴素的是可以直接遍历单链表得出长度之后再定位到链表中间,也可以使用双指针的方法,一个步长为1,一个步长为2,当步长为2的指针到达链表末尾时候步长为1的指针指向的就是单链表中间的位置;
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
int size = 0;
ListNode node = head;
while (node != null) {
node = node.next;
++size;
}
if (size <= 2) {
return;
}
int half = (size + 1) / 2;
node = head;
for (int i = 1; i < half; ++i) {
node = node.next;
}
ListNode first = head;
ListNode second = reverse(node.next);
node.next = null;
ListNode temp1 = null, temp2 = null;
while (second != null) {
temp1 = first.next;
temp2 = second.next;
first.next = second;
second.next = temp1;
first = temp1;
second = temp2;
}
}
public ListNode reverse(ListNode node) {
ListNode pre = null, now = node;
ListNode temp = null;
while (now.next != null) {
temp = now.next;
now.next = pre;
pre = now;
now = temp;
// next = next.next;
}
now.next = pre;
return now;
}
}