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
.
思路:
设置两个链表头,遍历原链表,一个追加小数链表,一个追加大数链表,最后将小数链表粘到大数链表前边即为结果。
C++:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* partition(ListNode* head, int x) { 12 if(head == 0) 13 return 0; 14 15 ListNode* pless = 0; 16 ListNode* plesshead = 0; 17 ListNode* pgreat = 0; 18 ListNode* pgreathead = 0; 19 ListNode* phead = head; 20 21 while(phead != 0) 22 { 23 if(phead->val < x) 24 { 25 if(pless == 0) 26 { 27 pless = phead; 28 plesshead = pless; 29 } 30 else 31 { 32 pless->next = phead; 33 pless = pless->next; 34 } 35 } 36 else 37 { 38 if(pgreat == 0) 39 { 40 pgreat = phead; 41 pgreathead = pgreat; 42 } 43 else 44 { 45 pgreat->next = phead; 46 pgreat = pgreat->next; 47 } 48 } 49 50 phead = phead->next; 51 } 52 53 if(plesshead == 0) 54 return pgreathead; 55 56 if(pgreathead == 0) 57 return plesshead; 58 59 pless->next = pgreat->next = 0; 60 pless->next = pgreathead; 61 62 return plesshead; 63 } 64 };
时间: 2024-10-25 17:31:08