【数据结构】循环链表

版权声明:无意呢。 https://blog.csdn.net/qq_41900081/article/details/86549981

循环链表

循环链表与普通链表的操作非常相似,只不过循环链表没有采用NULL值表示链表的结束,所以当遍历循环链表的时候要特别小心,否则将会无限地遍历链表,因为在循环链表中每个结点都有后继结点,最后一个结点的后继结点为表头结点。所以循环链表的遍历的结束条件为curentNode == headNode

主要操作

  1. 统计循环链表的结点个数
  2. 插入操作
    1)前插
    2)尾插
    3)中间插入
  3. 删除操作
    1)删除头结点
    2)删除尾结点
    3)删除中间结点

单循环链表

package dataStructure;

class CCLNode{
	int data;
	CCLNode next = this;
	
	//创建节点
	public CCLNode(int d) {
		data = d;
		
	}
}

public class CCList {
	
	//单循环链表的头结点
	CCLNode head;
	
	public CCList() {
		head = null;
	}
	
	//计算单循环链表长度
	int ListLength() {
		int length = 0;
		CCLNode currentNode = head;
		
		// 遍历单循环链表
		while(currentNode != null) {
			length++;
			currentNode = currentNode.next;
			if(currentNode == head)  break;
			
		}
		return length;
	}
	//打印单循环链表
	 void Print() {
		CCLNode cur = head;
		if(head == null) {
			System.out.print("null");
		}
		while(cur != null) {
			System.out.print(cur.data+"->");
			cur = cur.next;		
			if(cur == head)  break;
		}
		System.out.println();
	}
	
	//单循环链表的插入
	CCLNode Insert(CCLNode node,int position) {
		
		if(head == null ) {	
			head = node;
			return head; 
		}
		
		int size = ListLength();
		if(position < 1 || position > size+1) {
			System.out.println("违法插入");
			return head;
		}
		
		if(position == 1) {
			CCLNode cur = head;
			while(cur.next != head) {
				cur = cur.next;
			}
			node.next = head;
			cur.next = node;
			head = node;
			return head;
		}else {
			int count = 1;
			CCLNode it = head;
			//找到插入的位置的前一个结点
			while(count < position-1) {
				it = it.next;
				count++;		
			}
			node.next = it.next;
			it.next = node;
		}
		return head;
		
	}
	//删除单循环链表指定的结点
	CCLNode deleteNode(int position) {
		CCLNode it = head;
		int size = ListLength();
		
		if(position > size || position < 1) {
			System.out.println("违法删除");
			return head;
		}
		
		if(position == 1) {
			CCLNode rear = head;
			while(rear.next != head) {
				rear = rear.next;
			}
 			CCLNode currentNode = head.next;
 			rear.next = currentNode;
			head = currentNode;
			return currentNode;
		}else { 
			int count = 1;
			while(count < position-1) {
				it = it.next;
				count++;
			}
			it.next =it.next.next;
						
		}
		
		return head;
	}
	
	//删除整个单循环链表
	CCLNode deleteSingList() {
		CCLNode cur = head;
		CCLNode rear = head;
		
		while(cur.next != head) {
			rear = cur.next;
			cur= null;
			cur = rear;
		}
		head = null;
		return head;
	}
	
	public static void main(String[] args) {
		CCList list = new CCList();
		
		list.Insert(new CCLNode(1),2);
	    list.Insert(new CCLNode(3),2);
	    list.Insert(new CCLNode(2),2);
		list.Print();
	    list.deleteNode(1);
		list.Print();
		list.deleteSingList();
		list.Print();
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41900081/article/details/86549981