LeetCode Solution-86
Posted littledy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Solution-86相关的知识,希望对你有一定的参考价值。
86. 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.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
思路:
分别用2个链表存储小于x的值和大于等于x的值,然后将两个链表连接起来。注意要将第二个链表尾节点的下一个设为空,不然会出现链表无限循环的情况。
Solution:
ListNode* partition(ListNode* head, int x) {
ListNode node1(0), node2(0);
ListNode *p1 = &node1, *p2 = &node2;
while (head) {
if (head->val < x)
p1 = p1->next = head;
else
p2 = p2->next = head;
head = head->next;
}
p1->next = node2.next;
p2->next = NULL;
return node1.next;
}
性能:
Runtime: 8 ms??Memory Usage: 9.2 MB
以上是关于LeetCode Solution-86的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode810. 黑板异或游戏/455. 分发饼干/剑指Offer 53 - I. 在排序数组中查找数字 I/53 - II. 0~n-1中缺失的数字/54. 二叉搜索树的第k大节点(代码片段