Partition List
2013-11-09 17:42
162 查看
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given
return
思路:
用两个指针less和greater分别保存小于x和大于x的列表,然后遍历一遍,一边遍历一边更新这两个指针。
代码:
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given
1->4->3->2->5->2and x = 3,
return
1->2->2->4->3->5.
思路:
用两个指针less和greater分别保存小于x和大于x的列表,然后遍历一遍,一边遍历一边更新这两个指针。
代码:
ListNode *partition(ListNode *head, int x) { // Note: The Solution object is instantiated only once and is reused by each test case. if(head == NULL) return NULL; ListNode *less=NULL, *greater=NULL; ListNode *newhead = head, *greaterhead = NULL; while(head){ ListNode *tmp = head->next; if(head->val < x){ if(less == NULL){ less = head; newhead = less; } else{ head->next = less->next; less->next = head; less = less->next; } } else{ if(greater == NULL){ greaterhead = head; greater = head; greater->next = NULL; } else{ greater->next = head; greater = greater->next; greater->next = NULL; } } head = tmp; } if(less) less->next = greaterhead; return newhead; }
相关文章推荐
- LeetCode: Partition List
- Partition List
- Partition List
- Partition List
- [leetcode]Partition List
- 【Leetcode】Partition List
- [leetcode] Partition List
- LeetCode-Partition List
- LeetCode 086 Partition List
- [Leetcode] Partition List
- LeetCode[Linked List]: Partition List
- LeetCode OJ 之 Partition List (划分链表)
- Partition List
- LeetCode - Refresh - Partition List
- (LeetCode 86)Partition List
- leetcode--Partition List
- Partition List
- [leetcode-86]Partition List(c)
- LeetCode(86) Partition List
- [LeetCode]Partition List