Java(双向回环链表 + 面向对象)解决数三去一问题

in 编程
关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9

代码如下:

public class Count3Quit {
	public static void main(String[] args) {
		KidCircle kc = new KidCircle(500);
		Kid k = kc.getFirst();
		int countNum = 0;
		while (kc.getCount() > 1) {
			countNum++;
			if (countNum == 3) {
				countNum = 0;
				kc.delOneKid(k);
			}
			k = k.getRight();
		}
		System.out.println(kc.getFirst().getId());
	}
}

class Kid {
	private int id;
	private Kid left;
	private Kid right;
	
	Kid(int id) {
		this.id = id;
	}
	
	void setLeft(Kid k) {
		this.left = k;
	}
	
	void setRight(Kid k) {
		this.right = k;
	}
	
	Kid getLeft() {
		return this.left;
	}
	
	Kid getRight() {
		return this.right;
	}
	
	int getId() {
		return this.id;
	}
}

class KidCircle {
	private int size;
	private int count = 0;
	private Kid first, last;
	
	KidCircle(int size) {
		this.size = size;
		for (int i = 0; i < size; i++) {
			addOneKid();
		}
	}
	
	void addOneKid() {
		Kid k = new Kid(count);
		if (count <= 0) {
			first = k;
			last = k;
			k.setLeft(k);
			k.setRight(k);
		} else {
			last.setRight(k);
			k.setLeft(last);
			k.setRight(first);
			first.setLeft(k);
			last = k;
		}
		count++;
	}
	
	void delOneKid(Kid k) {
		if (count <= 0) {
			return;
		} else if (count == 1) {
			first = last = null;
		} else {
			k.getLeft().setRight(k.getRight());
			k.getRight().setLeft(k.getLeft());
			if (k == first) {
				first = k.getRight();
			} else if (k == last) {
				last = k.getLeft();
			}
		}
		count--;
	}
	
	Kid getFirst() {
		return this.first;
	}
	
	int getCount() {
		return this.count;
	}
}

 

关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9
扫一扫关注公众号添加购物返利助手,领红包
Comments are closed.

推荐使用阿里云服务器

超多优惠券

服务器最低一折,一年不到100!

朕已阅去看看