2.4

Topic: Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x.

// 方法1:向前插入(insert in front of A and B)Create two different linked list, one for elements less than x, one for greater or equal to x. 

// 方法2:向后插入 (insert into the end of A and B)。这种方法需要四个指针,每个list都要控制头尾。(four different variables to track two linked lists)

public class List {
	int data;
    List next;

    public List(int d) {
        this.data = d;
        this.next = null;
    }
    
    void appendToTail(int d) {//依次在最后一个节点的后面追加元素
        List end = new List(d);
        List n = this;
        while (n.next != null) {//判断是否是最后一个节点,如果不是,往后移
            n = n.next;
        }
        n.next = end;//把这个节点设为最后一个节点
    }
    
    void print() {
        List n = this;
        System.out.print("{");
        while (n != null) {
            if (n.next != null)
                System.out.print(n.data + ", ");
            else
                System.out.println(n.data + "}");
            n = n.next;
        }
    }
    
   public static List partition1(List list, int x){
	   List A=null;
	   List B=null;
	   
	   while(list!=null){
		   List next=list.next;//下一个节点一定要先存起来,后面这个节点就变成新链表了
		   if(list.data<x){
			   //向前插入
			   list.next=A;
			   A=list;
			   }
		   else{
			   list.next=B;
			   B=list;
			   }
	       list=next;
	       }
           if(A==null)	{return B;}
           //要记得先找到A的尾节点; 同时记得把A的起点存起来,不然会丢掉
           List A_head=A;
            while(A.next!=null){
            	A=A.next;
            }
           A.next=B;
           return A_head;//记得要返回链表的头,此时A在链表的中间	   
}
    
    public static void main(String args[]) {
        List list = new List(0);
        list.appendToTail(5);
        list.appendToTail(1);
        list.appendToTail(3);
        list.appendToTail(4);
        list.appendToTail(2);
        list.print();
        partition1(list,3).print();//这里注意不能直接打list.print(), 而应该print A
    }
}
//结果
{0, 5, 1, 3, 4, 2}
{2, 1, 0, 4, 3, 5}



 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值