标签:
题目描述:(链接)
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 ListNode left(-1); 13 ListNode right(-1); 14 15 ListNode *pLeft = &left; 16 ListNode *pRight = &right; 17 for (ListNode *cur = head; cur != NULL; cur = cur->next) { 18 if (cur->val < x) { 19 pLeft->next = cur; 20 pLeft = cur; 21 } else { 22 pRight->next = cur; 23 pRight = cur; 24 } 25 } 26 27 pLeft->next = right.next; 28 pRight->next = NULL; 29 30 return left.next; 31 } 32 };
标签:
原文地址:http://www.cnblogs.com/skycore/p/4903122.html