简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
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
Given
{1,2,3,4}
, reorder it to {1,4,2,3}
.
Basic idea,
1. get length of the linked list
2. go to the middle node of the list
3. reverse the bottom part of the list, set NULL to last node of upper part list, and NULL to the first node of bottom part list
4. insert one by one
Pay attention to the corner case. One is when we have odd number of elements in list, we have one node more in bottom part. The other case is we have only one node in bottom part when reversing.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) { | |
// IMPORTANT: Please reset any member data you declared, as | |
// the same Solution instance will be reused for each test case. | |
if(head==NULL||head->next==NULL) return; | |
ListNode *safeG = new ListNode(-1); | |
safeG->next = head; | |
int len = 0; ListNode *p = head; | |
while(p){ | |
len++; | |
p = p->next; | |
} | |
len/=2; p = head; | |
while(len){ | |
if(len==1) { | |
ListNode *tmp = p->next; | |
p->next = NULL; | |
p = tmp; | |
break; | |
} | |
len--; | |
p = p->next; | |
} | |
ListNode *pre = p; | |
p = p->next; | |
pre->next = NULL; | |
if(p){ | |
while(p){ | |
ListNode *tmp = p->next; | |
p->next = pre; | |
if(tmp==NULL) break; | |
pre = p; | |
p = tmp; | |
} | |
} | |
else | |
{ | |
p = pre; | |
} | |
pre = safeG->next; | |
while(pre&&p) | |
{ | |
ListNode *tmp1 = pre->next, *tmp2 = p->next; | |
pre->next = p; | |
if(tmp1==NULL) break; | |
p->next = tmp1; | |
pre=tmp1; | |
p=tmp2; | |
} | |
delete safeG; | |
} | |
}; |
好复杂啊
ReplyDelete思路不复杂,就是corner case有一点儿
Delete