cc150 --链表分割

题目描述

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

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

设置两个链表头,遍历原链表,一个追加小数链表,一个追加大数链表,最后将小数链表粘到大数链表前边即为结果。

 1 public class Partition {
 2     public ListNode partition(ListNode head, int x) {
 3         // write code here
 4         ListNode small = new ListNode(-1);
 5         ListNode big = new ListNode(-1);
 6         ListNode smallHead = small;
 7         ListNode bigHead = big;
 8         while(head!=null){
 9             if(head.val<x){
10                 small.next = head;
11                 small = small.next;
12                 head = head.next;
13                 small.next = null;
14             }
15             else{
16                 big.next = head;
17                 big = big.next;
18                 head = head.next;
19                 big.next = null;           
20             }
21         }
22         
23         if(bigHead.next==null) return smallHead.next;
24         if(smallHead.next==null) return bigHead.next;
25         
26         
27         //连接2个
28         ListNode cur = smallHead;
29         while(cur.next!=null)
30             cur = cur.next;
31         cur.next = bigHead.next;
32         return smallHead.next;
33     }
34 }
原文地址:https://www.cnblogs.com/zle1992/p/9018446.html