CCI 2.4 以某数为基准分割链表

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

package test;

public class DivideList {

	public Node divideList(Node head, int x){
		if(head==null || head.next==null)
			return head;
		Node newHead = new Node(0);
		newHead.next = head;
		Node smallHead = new Node(0);
		Node smallTail = smallHead;
		Node largeHead = new Node(0);
		Node largeHead = largeHead;
		while(newHead.next != null){
			if(newHead.next.val < x){
				smallTail.next = newHead.next;
				newHead.next = newHead.next.next;
				smallTail = smallTail.next;
				smallTail.next = null; //保持每次操纵尾部都指向null
			}else{
				largeTail.next = largeTail.next;
				newHead.next = newHead.next.next;
				largeTail = largeTail.next;
				largeTail.next = null;
			}
		}
		smallTail.next = largeHead.next;
		return smallHead.next;
	}
}


你可能感兴趣的:(链表)