leetcode : 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的节点插入到less链表,大于x的插入到greater链表,然后将两个链表连接即可。
注意把链表最后一个节点的next指针修改为NULL,防止出现环
代码:
class Solution { public: ListNode *partition(ListNode *head, int x) { ListNode *less = NULL,*greater = NULL; ListNode *p1 = NULL, *p2 = NULL; ListNode *h = head; while(h){ if(h->val < x){ if(!less){ less = h; }else{ p1->next = h; } p1 = h; }else{ if(!greater){ greater = h; }else{ p2->next = h; } p2 = h; } h = h->next; } if(less){ //连接两个链表 head = less; if(p1) p1->next = greater; }else head = greater; if(p2) //防止出现环 p2->next = NULL; return head; } };
浙公网安备 33010602011771号