Leetcode_86_Partition List
2016-04-11 17:37
363 查看
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小,后半部分比x大,但是不允许改变链表原本的顺序。
思路:建两个空链表,一个放大的,一个放小的,然后最后把他们连起来就行了。
坑:连接的时候要把greater指针的next清空然后再用,less的next指向greater的头指针,否则容易出现死循环。
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小,后半部分比x大,但是不允许改变链表原本的顺序。
思路:建两个空链表,一个放大的,一个放小的,然后最后把他们连起来就行了。
坑:连接的时候要把greater指针的next清空然后再用,less的next指向greater的头指针,否则容易出现死循环。
/** * 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 *ans = getAns(head, x); return ans; } ListNode* getAns(ListNode* head, int x) { ListNode *less_h = NULL; ListNode *greater_h = NULL; ListNode *less = NULL; ListNode *greater = NULL; ListNode *iter = head; while(iter!=NULL) { if(iter->val<x) { if(less_h == NULL) { less_h = iter; less = iter; } else { less->next = iter; less = less->next; } } else { if(greater_h == NULL) { greater_h = iter; greater = iter; } else { greater->next = iter; greater = greater->next; } } iter = iter->next; } if(greater!=NULL) greater->next = NULL; if(less_h == NULL) return greater_h; else { less->next = greater_h; return less_h; } } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- 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
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解