循环链表(思路+代码)

变量:

first、curboy(主要是这两个)

思路:

first是循环链表的头结点

curBoy是当前结点

无头结点,先打印后判断

代码:

public class Test {
	public static void main(String[] args) {
		CirList cirList = new CirList();
		cirList.add(5);
		cirList.show();
	}
}
class CirList{
	CirNode first = null;
	public void add(int nums) {
		if(nums < 1) {
			System.out.print("数字不正确!");
			return;
		}else {
			CirNode cur = null;
			for(int i = 1; i <= nums; i++) {
				CirNode boy = new CirNode(i);
				if(i == 1) {
					first = boy;
					cur = first;
					boy.setNext(first);
				}else {
					cur.setNext(boy);
					cur = boy;
					boy.setNext(first);
				}
			}
		}
	}
	public void show() {
		if(first.getNext() == null) {
			System.out.print("循环链表为空!");
			return;
		}
		CirNode cur = first;
		while(true) {
			System.out.println(cur);
			cur = cur.getNext();
			if(cur == this.first) {
				break;
			}
		}
	}
}
class CirNode{
	private int no;
	private CirNode next;
	public CirNode(int no){
		this.no = no;
	}
	public int getNo() {
		return no;
	}


	public void setNo(int no) {
		this.no = no;
	}


	public CirNode getNext() {
		return next;
	}


	public void setNext(CirNode next) {
		this.next = next;
	}
	


	@Override
	public String toString() {
		return "HeroNode2 [no=" + this.no + "]";
	}
}

猜你喜欢

转载自blog.csdn.net/qq_56127002/article/details/131547733