1、题目:
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
2、解答:该题目的意思是 链表原地修改。问题的解可以分为三步:1、找到链表的中间结点 2、把中间结点到尾结点进行反转,也就是链表的指向反转 3、合并两个链表
3、C++代码
class Solution {
public:
void reorderList(ListNode* head) {
ListNode *slow ,*fast;
ListNode *preNode,*curNode;
if(!head || !head->next){
return ;
}else{
//求中间结点
slow = head;
fast = head->next;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
}
fast = slow->next; //fast to end
slow->next = NULL;
preNode = NULL;
//第二个链表的逆序
while(fast){
curNode = fast->next;
fast->next = preNode;
preNode = fast;
fast = curNode;
}
fast = preNode;
slow = head;
//合并两个链表
while(fast){
ListNode *temp1 = slow->next;
ListNode *temp2 = fast->next;
fast->next = slow->next;
slow->next = fast;
slow = temp1;
fast = temp2;
}
}
}
};
python代码
class Solution:
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
if head is None or head.next is None:
return
else:
//找链表的中间位置
slow,fast = head,head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
fast = slow.next
slow.next = None
preNode = None
while fast:
temp = fast.next
fast.next = preNode
preNode = fast
fast = temp
slow = head
fast = preNode
while fast:
temp1 = slow.next
temp2 = fast.next
fast.next = slow.next
slow.next = fast
slow = temp1
fast = temp2
return