leetcode 86.分隔链表
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3 输出: 1->2->2->4->3->5
思路:
(1)新建两个ListNode节点,分别用这两个节点,去接对应的节点,用head遍历链表;
(2)大的放大的后面,pmore->next=head;pmore=head; 小的放小的后面,pless->next=head;pless=head;
(3)连接两者,尾部置空,返回头部;
代码:
1 #include<iostream> 2 using namespace std; 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 less_head(0); 13 ListNode more_head(0); 14 ListNode* pless = &less_head; 15 ListNode* pmore = &more_head; 16 while (head) { 17 if (head->val < x) { 18 pless->next = head; 19 pless = head; 20 } 21 else 22 { 23 pmore->next = head; 24 pmore = head; 25 } 26 head = head->next; 27 } 28 pless->next = more_head.next; 29 pmore->next = NULL; 30 return less_head.next; 31 } 32 }; 33 34 //测试 35 int main() 36 { 37 ListNode a(1); 38 ListNode b(7); 39 ListNode c(10); 40 ListNode d(17); 41 ListNode e(2); 42 ListNode f(5); 43 a.next = &b; 44 b.next = &c; 45 c.next = &d; 46 d.next = &e; 47 e.next = &f; 48 f.next = NULL; 49 Solution solve; 50 ListNode* head = solve.partition(&a, 8); 51 while (head) { 52 printf("%d\n", head->val); 53 head = head->next; 54 } 55 system("pause"); 56 return 0; 57 }

浙公网安备 33010602011771号