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.

Solution: 建立两个链表,一个存值比x小的,一个存值比x大的,然后将两个链表连起来。

要将值大的那个表的最后一个数的next = null。

在建链表的时候我采用了头指针的方式。(-1那个指针)

 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         // Start typing your Java solution below
15         // DO NOT write main() function
16         if(head == null) return head;
17         ListNode small = new ListNode(-1);
18         ListNode large = new ListNode(-1);
19         ListNode scur = small;
20         ListNode lcur = large;
21         while(head != null){
22             if(head.val < x){
23                 scur.next = head;
24                 scur = head;
25             }else{
26                 lcur.next = head;
27                 lcur = head;
28             }
29             head = head.next;
30         }
31         scur.next = large.next;
32         lcur.next = null;
33         return small.next;
34     }
35 }

 第二遍: 就在原来链表上修改。 将大于target的数字放到原来list的tail处。

 1 public class Solution {
 2     public ListNode partition(ListNode head, int x) {
 3         // IMPORTANT: Please reset any member data you declared, as
 4         // the same Solution instance will be reused for each test case.
 5         ListNode header = new ListNode(-1);
 6         header.next = head;
 7         int len = 0;
 8         ListNode cur = header, tail = null;
 9         while(cur.next != null){
10             cur = cur.next;
11             len ++;
12         }
13         tail = cur;
14         cur = header;
15         int i = 0;
16         while(i < len){
17             if(cur.next.val >= x){
18                 tail.next = cur.next;
19                 cur.next = cur.next.next;
20                 tail = tail.next;
21                 tail.next = null;
22             }else{
23                 cur = cur.next;
24             }
25             i ++;
26         }
27         return header.next;
28     }
29 }

 

posted on 2013-09-26 12:09  Step-BY-Step  阅读(253)  评论(0编辑  收藏  举报

导航