码迷,mamicode.com
首页 > 其他好文 > 详细

链表分割

时间:2016-03-31 20:26:18      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

题目描述

编写代码,以给定值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 }

 

链表分割

标签:

原文地址:http://www.cnblogs.com/xiaoyesoso/p/5342485.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!