Leetcode#86 Partition List

原题地址

 

凡是涉及链表的题目,代码越清楚越好。

 

代码:

 1 ListNode *partition(ListNode *head, int x) {
 2         ListNode *ltHead = NULL;
 3         ListNode *ltTail = NULL;
 4         ListNode *geHead = NULL;
 5         ListNode *geTail = NULL;
 6         
 7         while (head) {
 8             if (head->val < x) {
 9                 if (!ltHead)
10                     ltHead = ltTail = head;
11                 else {
12                     ltTail->next = head;
13                     ltTail = ltTail->next;
14                 }
15             }
16             else {
17                 if (!geHead)
18                     geHead = geTail = head;
19                 else {
20                     geTail->next = head;
21                     geTail = geTail->next;
22                 }
23             }
24             head = head->next;
25         }
26         
27         if (ltTail)
28             ltTail->next = geHead;
29         if (geTail)
30             geTail->next = NULL;
31             
32         return ltHead ? ltHead : geHead;
33 }

 

posted @ 2015-01-29 11:06  李舜阳  阅读(186)  评论(0编辑  收藏  举报