循环链表的实现

Posted by Ruizhi Ma on May 19, 2019

LoopNode类

package demo2;

public class LoopNode {
	//节点的内容
	int data;
	
	//下一个节点的索引 
	LoopNode nextAddress = this;
	
	public LoopNode(int data){
		this.data = data;
	}
	
	//插入一个节点
		public void after(LoopNode node){
			//取出下个节点,作为下下个节点
			LoopNode nextNext = nextAddress;
			
			//将新节点设置为下个节点
			this.nextAddress = node;
			
			//将下下个节点设置为新节点的下个节点
			node.nextAddress = nextNext;
		}
	
	//删除一个节点
	public void removeNext(){
		//找到下下个节点
		LoopNode newNode = this.nextAddress.nextAddress;
		//用下下个节点,替换下个节点
		this.nextAddress = newNode;
	}
	
	//获取节点内容
	public int getData(){
		return this.data;
	}
	
	//获取下一个节点
	public LoopNode next(){
		return this.nextAddress;
	}
}


TestLoopNode类

package demo2.test;

import demo2.LoopNode;

public class TestLoopNode {

	public static void main(String[] args) {
		//创建节点
		LoopNode n1 = new LoopNode(1);
		LoopNode n2 = new LoopNode(2);
		LoopNode n3 = new LoopNode(3);
		LoopNode n4 = new LoopNode(4);
		
		//增加节点
		n1.after(n2);
		n2.after(n3);
		n3.after(n4);
		System.out.println(n1.next().getData());
		System.out.println(n2.next().getData());
		System.out.println(n3.next().getData());
		System.out.println(n4.next().getData());
		
	}

}


问题解惑

我在第三个连上去的时候,有点犯迷糊,觉得第三个节点应该连上第二个节点。其实把LoopNode nextNext = nextAddress;看成LoopNode nextNext = this.nextAddress;就好理解了,其实第二个节点指向的是第一个,所以还是把第一个节点赋值给了nextNext,这样一来,收尾就连上去了。

运行结果:
2
3
4
1