首页 > 其他 > 详细

leetcode------Partition List

时间:2015-03-29 17:46:39      阅读:207      评论:0      收藏:0      [点我收藏+]
标题: Partition List
通过率: 27.5%
难度: 中等

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.

本题就是利用一个target将链表分成两部分,小于target和大于target的

用两个链表进行记录,small和big进行连接时候一定要将.next置null,否则内存会一直叠加。连接的过程就是指针的重定向过程,所以一定要置null,要不然会讲整个链表连接过来,代码如下:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode partition(ListNode head, int x) {
14         ListNode small=new ListNode(1);
15         ListNode big=new ListNode(1);
16         ListNode s=small,b=big;
17         if(head==null)return head;
18         while(head!=null){
19             if(head.val<x){
20                 s.next=head;
21                 head=head.next;
22                 s=s.next;
23                 s.next=null;
24             }
25             else{
26                 b.next=head;
27                 head=head.next;
28                 b=b.next;
29                 b.next=null;
30             }
31         }
32         s.next=big.next;
33         return small.next;
34     }
35 }

 

leetcode------Partition List

原文:http://www.cnblogs.com/pkuYang/p/4375820.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!