题目描述:
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的节点放在前面,大于x的节点放在后面,而且这两部分都要按照原来的顺序排列。
解题思路:
既然要求是分割链表成两个部分,那么我们就可以把这两个部分先分开储存,最后再结合在一起。
代码:
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 || !head->next) 13 return head; 14 ListNode *head1 = new ListNode(0), *head2 = new ListNode(0), *p1 = head1, *p2 = head2; //p1和p2指针用于遍历链表储存两个部分,head1和head2用于存储开头 15 while(head){ 16 //遍历链表 17 if(head->val < x){ 18 //小于的部分 19 p1->next = head; 20 p1 = head; 21 } 22 else{ 23 //大于的部分 24 p2->next = head; 25 p2 = head; 26 } 27 head = head->next; 28 } 29 p1->next = head2->next;//将小于部分的末尾连接大于部分的开头 30 p2->next = NULL;//大于部分的结果给上一个NULL 31 return head1->next; 32 } 33 };