Partition List

Link: http://oj.leetcode.com/problems/partition-list/

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.

 

 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 remains = new ListNode(0);
15         ListNode remains_point = remains;
16         ListNode result = new ListNode(0);
17         ListNode result_point = result;
18         while(head!=null){
19             if(head.val<x) {
20                 result.next = head;
21                 result = result.next;
22                 head = head.next;
23             }else {
24                 remains.next=head;
25                 remains = remains.next;
26                 head = head.next;
27             }
28         }
29         if(remains_point.next!=null){
30             result.next=remains_point.next;
31             //Note we should end the remains link list
32             remains.next=null;
33         }
34         return result_point.next;
35     }
36 }

第一题提交没通过。因为remains链表没有加终止。

 

 

 

posted on 2014-05-02 00:57  Atlas-Zzz  阅读(110)  评论(0编辑  收藏  举报

导航