首页 > 代码库 > LeetCode86 Partition List
LeetCode86 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.(Medium)
For example,
Given 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
分析:
把链表归并,其思路就是先开两个链表,把小于x的值接在链表left后面,大于x的值接在链表right后面;
然后把链表left的尾部与链表right的头部接在一起。
注意:链表right的尾部next赋值为nullptr。
代码:
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 dummy1(0);13 ListNode dummy2(0);14 ListNode* left = &dummy1;15 ListNode* right = &dummy2;16 while (head != nullptr) {17 if (head -> val < x) {18 left -> next = head;19 left = left -> next;20 }21 else {22 right -> next = head;23 right = right -> next;24 }25 head = head -> next;26 }27 left -> next = dummy2.next;28 right -> next = nullptr;29 return dummy1.next;30 }31 };
LeetCode86 Partition List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。