86. Partition List
来源:互联网 发布:常用设计软件 编辑:程序博客网 时间:2024/06/06 18:57
Description:
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
.
分析:建立两个指针pass1和pass2, head指针遍历链表,小于x的Node链接到pass1上,大于x的Node链接到pass2上,最后把pass2接到pass1之后,返回pass1.(如果只用一个指针,则需要对链表进行删除这样的操作,会更复杂)。
代码如下:
/** * 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 new_head1(0), new_head2(0);//建立两个Node来保存两条链表的头结点 ListNode* pass1, *pass2; pass1 = &new_head1; pass2 = &new_head2; while(head) { if(head->val < x) { pass1->next = head; pass1 = pass1->next; } else { pass2->next = head; pass2 = pass2->next; } head = head->next; } pass2->next = NULL; pass1->next = new_head2.next; return new_head1.next; }};
阅读全文
0 0
- [LeetCode]86.Partition List
- LeetCode 86. Partition List
- [Leetcode] 86. Partition List
- LeetCode --- 86. Partition List
- 86. Partition List
- [leetcode] 86.Partition List
- [leetcode] 86. Partition List
- 86. Partition List
- [LeetCode]86. Partition List
- 86. Partition List
- 86. Partition List LeetCode
- 86. Partition List
- 86. Partition List
- 86. Partition List
- Leetcode 86. Partition List
- LeetCode *** 86. Partition List
- LeetCode 86. Partition List
- [LeetCode]86. Partition List
- 关于move_uploaded_file()出错的问题
- C语言局部变量与全局变量
- 第九天实训!!!
- 太乐地图下载器 V5.0.5 破解版
- 常见手势使用
- 86. Partition List
- vue 学习 1
- IT优先级2017:技术领导者仍然投资于云选项
- 快速排序
- String类型转 Map
- Hadoop调试:Exception in thread "main"java.lang.UnsatisfiedLinkError
- apscheduler modify_job能否修改更多参数
- leetcode分类题解
- Java复习总结3