Partition List -- leetcod
来源:互联网 发布:图论算法 python 编辑:程序博客网 时间:2024/05/16 14:15
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
.
基本思路:
1. 设置两个临时链表
2. 将小于x的节点,挂到一个链表上。将大于等于的节点,挂到另一个链表上。
3. 串接两个链表。将后一个链表的头部,挂以前一个链表的尾部。
所犯的错误:
初次提交时,漏写了
p2->next = 0;提交后,报告运行时间超出。
/** * 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 h1(0); ListNode h2(0); ListNode *p1 = &h1; ListNode *p2 = &h2; while (head) { if (head->val < x) { p1->next = head; p1 = p1->next; } else { p2->next = head; p2 = p2->next; } head = head->next; } p1->next = h2.next; p2->next = 0; // 此句漏写,将会在单链表中产生环。 return h1.next; }};
在leetcode讨论组中,有一个更简洁的写法。
https://leetcode.com/discuss/21032/very-concise-one-pass-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; } p2->next = NULL; p1->next = node2.next; return node1.next;}
使用连续赋值,将两句写成了一句。
0 0
- Partition List -- leetcod
- Reorder List leetcod
- leetcod
- LeetCod 339.Nested List Weight Sum
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Tomcat启动失败的问题
- XIB && NIB && IB 三者之间的关系
- linux正则表达式awk讲解
- 用数组和链表分别实现栈类stack,队queue
- android开发中结束所有的activity
- Partition List -- leetcod
- 一些数据结构高(hao)逼(wu)格(liao)的实现方法
- 单例模式
- Android常用适配器Adapter
- P122 20
- if中处填写什么使得结果为ab
- JavaScript闭包
- Android系统自定义Android Lollipop Theme
- POJ 1502MPI Maelstrom BFS最短路