标签:des c style class blog code
Partition List
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 1->4->3->2->5->2
and x =
3,
return 1->2->2->4->3->5
.
维护两个链表,一个记录比x小的(头newl, 尾left),一个记录不小于x的(头newr,尾right)。
扫描一遍链表,根据大小装入上述两个链表,最后将上述两个连起来即可。需要注意的是,最后一个节点的next需要设为NULL。
class Solution { public: ListNode *partition(ListNode *head, int x) { ListNode *left = NULL; ListNode *right = NULL; ListNode *newl = left; ListNode *newr = right; while(head != NULL) { if(head->val < x) { if(left == NULL) { left = head; newl = left; } else { left->next = head; left = left->next; } } else { if(right == NULL) { right = head; newr = right; } else { right->next = head; right = right->next; } } head = head->next; } if(newl == NULL) return newr; else { if(right != NULL) right->next = NULL; left->next = newr; return newl; } } };
【LeetCode】Partition List,布布扣,bubuko.com
标签:des c style class blog code
原文地址:http://www.cnblogs.com/ganganloveu/p/3770697.html