0
点赞
收藏
分享

微信扫一扫

java自写代码--单向循环链表基本操作

诗与泡面 2022-03-30 阅读 70

内含创建链表、插入、打印链表。其中插入还有不足,有点像删除操作了,日后继续学习后再改正。

//基于没有头结点的带尾指针的单循环链表的一些操作

public class connectNode {
	
	public int data;
	public connectNode next;
	public connectNode head;//头结点
	public connectNode last;//尾结点

	
	public connectNode() {
		head = new connectNode(-1);
		last = new connectNode(-1);
		head.next = head;//形成闭环
		last = head;
	}
	
	public connectNode(int data) {
		this.data = data;
	}
	
	//创建单循环链表
	public void createList(int data) {
		
		connectNode node = new connectNode(data);
		
		if(head.next==head) {//若为空
			head.next = node;
			node.next = head;
			last = node;
		}else {//若不为空
			last.next = node;
			node.next = head;
			last = node;
		}
    }
	
	//在index位置后插入一个结点
	public void addNode(int index,int data) {
		connectNode newNode = new connectNode(data);
		
		if(index<0) {//判断插入位置是否合法
			System.out.println("不合法");
			return;
		}
		
		int step = 0;
		connectNode temp;//我发现了这里有个bug,就是它无法自动存储遍历过的结点
		
		while(step!=index+1) {
			step++;
			head = head.next;
		 }
		
		newNode.next = head.next;
		head.next = newNode;
	}

	
	//打印单循环链表
	public void show() {
		
		while(last!=head) {
			System.out.print(head.next.data+" ");
			head = head.next;
		}
	}

	public static void main(String[] args) {
		connectNode list = new connectNode();
		list.createList(0);
		list.createList(1);
		list.createList(2);
		list.createList(3);
		list.createList(4);
		list.createList(5);
		list.show();
		System.out.println("\t");
		list.addNode(2, 9);
		list.show();
		
	}
}

举报

相关推荐

0 条评论