Java(雙向迴環鏈表 + 面向對象)解決數三去一問題

代碼以下:java

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;
	}
}
相關文章
相關標籤/搜索