LeetCode OJ Partition List
来源:互联网 发布:淘宝网店在哪里看 编辑:程序博客网 时间:2024/05/22 21:40
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
.
class Solution {public: ListNode *partition(ListNode *head, int x) { if (head == NULL) { return head; } if (head->next == NULL) { return head; } bool first_less = true; bool first_greater = true; ListNode *less_head = NULL; ListNode *less_tail = NULL; ListNode *greater_head = NULL; ListNode *greater_tail = NULL; ListNode *move = head; while (move != NULL) { if (move->val < x) { if (first_less) { first_less = false; less_head = new ListNode(move->val); less_tail = less_head; } else { ListNode *new_less = new ListNode(move->val); less_tail->next = new_less; less_tail = less_tail->next; } } else { if (first_greater) { first_greater = false; greater_head = new ListNode(move->val); greater_tail = greater_head; } else { ListNode *new_greater = new ListNode(move->val); greater_tail->next = new_greater; greater_tail = greater_tail->next; } } move = move->next; } move = head; ListNode *move_new = less_head; ListNode *del; while (move_new != NULL) { move->val = move_new->val; move = move->next; del = move_new; move_new = move_new->next; delete del; } move_new = greater_head; while (move_new != NULL) { move->val = move_new->val; move = move->next; del = move_new; move_new = move_new->next; delete del; } return head; }};
0 0
- LeetCode OJ:Partition List
- LeetCode OJ - Partition List
- LeetCode OJ Partition List
- <LeetCode OJ> 61 / 86 Rotate List / Partition List
- LeetCode OJ 之 Partition List (划分链表)
- LeetCode: Partition List
- LeetCode Partition List
- LeetCode: Partition List
- [Leetcode] Partition List **
- [Leetcode] Partition List
- [LeetCode] Partition List
- leetcode 81: Partition List
- [Leetcode] Partition List
- leetcode 118: Partition List
- [LeetCode]Partition List
- [leetcode]Partition List
- LeetCode-Partition List
- [leetcode] Partition List
- 字符串分割(C++)
- llinux 命令 ----每天一小时-01
- LeetCode OJ Reorder List
- CodeForces - 44B Cola
- C++中数字与字符串之间的转换
- LeetCode OJ Partition List
- java.io中的字符流简单介绍
- ZOJ1003(1)
- LeetCode OJ Reverse Linked List II
- LeetCode OJ Linked List Cycle II
- 每个Java程序员必须知道的5个JVM命令行标志
- LeetCode OJ Linked List Cycle
- leetcode 之Rotate Array
- LeetCode OJ Insertion Sort List