参考了网上答案
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}
.
分析:
先拆成两个子链,再组合起来。 第二条链需要反转
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return nothing
def reorderList(self, head):
if (head==None or head.next==None):
return head
slow = fast = head
while (fast.next!=None and fast.next.next!=None):
slow = slow.next
fast = fast.next.next
sec = slow.next
slow.next = None
if (sec!=None and sec.next!=None):
pre,cur,next = None, sec, sec.next
while True:
cur.next = pre
pre = cur
cur = next
if cur==None:
break;
next = cur.next
sec = pre
dummy = ListNode(100)
first,curr = head,dummy
while(sec!=None):
curr.next = first
curr = curr.next
first = first.next
curr.next = sec
curr = curr.next
sec = sec.next
if first!=None:
curr.next = first
curr = curr.next
curr.next = None
head = dummy.next
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode *head) {
if(head==NULL || head->next==NULL){return;}
ListNode *slow = head, *fast = head;
while(fast->next!=NULL && fast->next->next!=NULL){
slow = slow->next;
fast = fast->next->next;
}
ListNode *sec = slow->next;
slow->next = NULL;
if(sec->next!=NULL){
ListNode *next = sec->next;
ListNode *cur = sec;
ListNode *pre = NULL;
while(cur!=NULL){
cur->next = pre;
pre = cur;
cur = next;
if(cur==NULL){ break; }
next = cur->next;
}
sec = pre;
}
ListNode *dummy = new ListNode(100);
ListNode *first = head;
ListNode* cur = dummy;
while(sec!=NULL){
cur->next = first;
cur = cur->next;
first = first->next;
cur->next = sec;
cur = cur->next;
sec = sec->next;
}
if(first!=NULL){
cur->next = first;
cur = cur->next;
}
cur->next = NULL;
head = dummy->next;
}
};
总结:
1. ListNode *cur instead of ListNode* cur。 编译器会默认ListNode是一种类型,而不是ListNode*
2. 同一个类型下,可以写成 ListNode *cur = head, *fast = head, 可以连写
3. 函数最好写成 general 形式的,这样其它函数也可以调用。
4. void 的 return, 直接写成 return.。 同一行的 if 语句写成: if (fdsa) return; if 里如果只有一个语句,不用加括号
5. 定义在括号里的变良是local 变量,出了括号后不能使用。
6. 对一个小的子函数,也一定要先判断下边界条件。
7. 在脑子里把所有情况都想好,避免都写在纸上。