荷兰国旗问题(链表)

用三个桶,每个桶包括(链表的头和链表的尾),三个桶分别是Less, Equal, More.遍历一次链表把数值放入相应的桶。

public class Test_Demo {

	public static class Node{
		int value;
		Node next;
		
		public Node(int value) {
			this.value=value;
		}
	}
	public static Node LessEqualMore(Node head,int num) {
		if(head==null)
			return head;
		Node lessStart=null;
		Node lessEnd=null;//第一个桶
		Node equalStart=null;
		Node equalEnd=null;//第二个桶
		Node moreStart=null;
		Node moreEnd=null;//第三个桶
		Node next=null;
		while(head!=null)//遍历一次
		{
			next=head.next;
			head.next=null;
			if(head.value<num)
			{
				if(lessStart==null)
					lessStart=head;
				else
					lessEnd.next=head;
				lessEnd=head;
					
			}
			else if(head.value==num)
			{
				if(equalStart==null)
					equalStart=head;
				else
					equalEnd.next=head;
				equalEnd=head;
			}
			else if(head.value>num)
			{
				if(moreStart==null)
					moreStart=head;
				else
					moreEnd.next=head;
				moreEnd=head;
			}
			head=next;
		}
		
		if(lessEnd!=null)//拼接三个桶
		{
			if(equalStart!=null)
			{
				lessEnd.next=equalStart;
				if(moreStart!=null)
					equalEnd.next=moreStart;
			}
			else if(moreStart!=null)
				lessEnd.next=moreStart;
		}
		else if(equalEnd!=null)
		{
			if(moreStart!=null)
				equalEnd.next=moreStart;
		}
		return lessStart=lessStart==null?(equalStart==null?moreStart:equalStart):lessStart;//返回头结点
	}
	
	public static void printLinkedList(Node head) {
		System.out.println("The LinkedList is :");
		while(head!=null)
		{
			System.out.print(head.value+" ");
			head=head.next;
		}
		System.out.println();
	}
	public static void main(String[] args) {
		Node head = new Node(7);
		head.next = new Node(9);
		head.next.next = new Node(1);
		head.next.next.next = new Node(8);
		head.next.next.next.next = new Node(5);
		head.next.next.next.next.next = new Node(2);
		head.next.next.next.next.next.next = new Node(5);
		printLinkedList(head);
		head=LessEqualMore(head,5);
		printLinkedList(head);

	}

}

另一种方法就是把节点存入数组中,再根据数组的荷兰国旗问题求解。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值