Partition List
来源:互联网 发布:iphoneairplay连接mac 编辑:程序博客网 时间:2024/05/29 13:48
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的结点添加到新链表的尾部,然后在原链表中删除该结点,遍历完原链表之后,在新的链表的尾端加入原链表的头就可以了。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode partition(ListNode head, int x) { ListNode hr=new ListNode(-1); ListNode current=head; hr.next=head; ListNode pre=hr; ListNode less=new ListNode(-1); ListNode tail=less; while(current!=null) { if(current.val<x) { tail.next=new ListNode(current.val); tail=tail.next; pre.next=current.next; current=current.next; continue; } pre=current; current=current.next; } tail.next=hr.next; return less.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
- java复习(三)
- 几个iOS工程通用模块第三方类库介绍
- #305 (div.2) C. Mike and Frog
- 怎么样恢复别人删除的腾讯微博私信聊天内容
- 怎么做才可以把之前删除的微信聊天记录恢复
- Partition List
- poj 2763 树链剖分(单点更新,区间求值)
- jsp+js实现二级级联
- 怎样才能查看爱人的微信聊天记录QQ聊天记录
- 【移动语义和精准转发系列二】std::move和std::forward
- 如何计算IP地址的网络号和主机号?
- 怎样才能看到老公手机上已删除的QQ聊天记录
- Perl 若A则B判断的表示方法
- 3次握手4次挥手