[leetcode] 【链表】86. Partition List
2016-05-30 16:43
387 查看
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
return
Given
3,
return
同时,两部分的节点要保持原来链表的节点顺序。
最后把两个链表相连即可。
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given
1->4->3->2->5->2and x = 3,
return
1->2->2->4->3->5.
题意
给定一个值x,把链表中小于x的值放到大于等于x的值之前。即Given
1->4->3->2->5->2and x =
3,
return
1->2->2->4->3->5.
同时,两部分的节点要保持原来链表的节点顺序。
题解
创建两个链表,一个存储小的,一个存储大于等于的。最后把两个链表相连即可。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* partition(ListNode* head, int x) { ListNode small(-1); ListNode big(-1); auto small_p=&small; auto big_p=&big; for(ListNode *cur=head;cur;cur=cur->next) { if(cur->val<x) { small_p->next=cur; small_p=cur; } else { big_p->next=cur; big_p=cur; } } big_p->next=NULL; small_p->next=big.next; return small.next; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- C++中const用法总结
- CPP 虚函数、虚函数表及虚拟继承(转)
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- Deploying Control Plane Policing
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解