noaman_wgs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

【题目】

编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。

【代码】

import java.util.*;

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Partition {
    public ListNode partition(ListNode pHead, int x) {
        if (pHead == null)
            return pHead;
        
        ListNode curNode = pHead;
        ListNode smallNode = new ListNode(-1);
        ListNode smallHead = smallNode;
        ListNode bigNode = new ListNode(-1);
        ListNode bigHead = bigNode;
        
        while (curNode != null){
            if (curNode.val >= x){
               bigNode.next = curNode;
               bigNode = bigNode.next;
            } else {
               smallNode.next = curNode;
               smallNode = smallNode.next;
            }
            curNode = curNode.next;
        }
        
        smallNode.next = bigHead.next;
        bigNode.next = null;
        return smallHead.next;
        
        
        
    }
}

 

posted on 2017-06-06 10:08  noaman_wgs  阅读(172)  评论(0编辑  收藏  举报