leetcode笔记:Partition List
来源:互联网 发布:安卓新闻推荐 知乎 编辑:程序博客网 时间:2024/06/11 15:57
一. 题目描述
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
的前面,大于等于x
的放到x
的后面,每部分元素的原始相对位置不变。
该题是一个普通的链表遍历的题目,需要注意的地方在于必须将链表的最后一个节点的下一个节点更新为null,不然链表会出现环,从而导致死循环的情况。
三. 示例代码
#include <iostream>struct ListNode{ int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {}};class Solution{public: ListNode *partition(ListNode *head, int x) { ListNode *LessHeader = new ListNode(10); ListNode *LessTail = LessHeader; ListNode *GreaterHeader = new ListNode(10); ListNode *GreaterTail = GreaterHeader; while(head != NULL) { if (head->val < x) { LessTail->next = head; LessTail = head; } else { GreaterTail->next = head; GreaterTail = head; } head = head->next; } LessTail->next = GreaterHeader->next; GreaterTail->next = NULL; delete GreaterHeader; head = LessHeader->next; delete LessHeader; return head; }};
四. 小结
无
3 0
- leetcode笔记:Partition List
- leetcode笔记--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
- LeetCode - Partition List
- [LeetCode] Partition List
- LeetCode 86: Partition List
- JUnit编写单元测试代码注意点小结
- json常用的一些知识
- Android 屏幕适配
- DBCP、C3P0、Proxool 、 BoneCP开源连接池的比较
- Eclipse Debug 教程
- leetcode笔记:Partition List
- linux网络命令--1--ifconfig
- BNUOJ 51003 BQG's Confusing Sequence(二进制)
- 良好的异常展现界面<500.jsp>
- HDU 5602 Black Jack(博弈dp)
- 底部RadioButton实现Fragment切换
- Handler进程之间通信
- Looper类、主线程工作线程通信
- Activity切换中Intent传递数据、对象