partition-list
来源:互联网 发布:买家淘宝购物流程 编辑:程序博客网 时间:2024/06/02 17:39
容易 链表划分
31%
通过
给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。
你应该保留两部分内链表节点原有的相对顺序。
Yes
样例
给定链表 1->4->3->2->5->2->null,并且 x=3
返回 1->2->2->4->3->5->null
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The first node of linked list. * @param x: an integer * @return: a ListNode */ public ListNode partition(ListNode head, int x) { if(head == null){ return null; } /** * 建两个dummyNode, 作为两个链表的开始 */ ListNode beforeDummy = new ListNode(0); ListNode afterDummy = new ListNode(0); /** * before和after相当于指针 * 开始的时候分别指向beforeDummy和afterDummy * */ ListNode before = beforeDummy,after = afterDummy; while(head != null){ if(head.val < x){ /** * 最开始的时候before指向beforeDummy, before.next = head * 相当于把head添加到before链表中 * before.next = head; * before = head; 等于添加完了head后,将before指针指向head * 也就是before链表的末尾 */ before.next = head; before = head; }else{ /** * after的操作同before * 只是当head的val大于x的时候添加到after链表 */ after.next = head; after = head; } head = head.next; } /** * 合并两个链表 * after接到before的后面 */ after.next = null; before.next = afterDummy.next;//affterDummy和beforeDummy一直都没变 //afterDummy.next指向after的第一个元素 //beforeDummy.next指向before的第一个元素 return beforeDummy.next; }}
0 0
- 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
- Partition List
- Partition List
- Partition List
- Partition List
- 阶与原根学习笔记
- LeetCode 226 Invert Binary Tree
- css sprite的实现
- 正确增加Cloneable接口
- uva10820(简单数学题)
- partition-list
- apache2.4 以上的版本,cgi-bin中的文件不能运行。
- ios tableView性能优化策略
- 我也开博客了……
- 非你莫属 周倩如 女程序员 神一样的选手!
- maven编译代码详细介绍
- 抢测试1
- TopCoder SRM 661 Div2 Problem 500 - BridgeBuildingDiv2 (枚举 + 状态压缩)
- Doubles