链表分割

题目描述

编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前

给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。

 

 1 import java.util.*;
 2 
 3 /*
 4 public class ListNode {
 5     int val;
 6     ListNode next = null;
 7 
 8     ListNode(int val) {
 9         this.val = val;
10     }
11 }*/
12 public class Partition {
13     public ListNode partition(ListNode pHead, int x) {
14         // write code here
15         ListNode beforeBg = null, beforeEd = null,
16                 afterBg = null,afterEd = null;
17         while(pHead != null)
18         {
19             ListNode next = pHead.next;
20             pHead.next = null;
21             if(pHead.val <x)
22             {
23                 if(beforeBg == null)
24                 {
25                     beforeBg = pHead;
26                     beforeEd = pHead;
27                 }
28                 else
29                 {
30                     beforeEd.next = pHead;
31                     beforeEd = pHead;
32                 }
33             }
34             else
35             {
36                 if(afterBg == null)
37                 {
38                     afterBg = pHead;
39                     afterEd = pHead;
40                 }
41                 else
42                 {
43                     afterEd.next = pHead;
44                     afterEd = pHead;
45                 }
46             }
47             pHead = next;
48         }
49         
50         if(beforeBg == null) return afterBg;
51         beforeEd.next = afterBg;
52         return beforeBg;
53     }
54 }

 

posted @ 2016-03-31 19:47  小爷  阅读(254)  评论(0编辑  收藏  举报