根据上次实现了单向链表,我们已经知道了链表的基本格式,就像线由点构成一样,链表由无数个节点构成。而这个循环链表的基本格式跟单向链表差不多,两者的差别就在于最后一个节点的next的指向。
如图所示此时最后一个节点的next又指向了第一个节点形成一个循环。
直接上代码:
public LNode CreateList(int n){
LNode cur=null; //用于储存当前节点
LNode head =null; //初始化一个头节点用于记录
//尾插法实现循环链表的创立
for(int i=1;i<=n;i++){
LNode newNode = new LNode(i);
if(this.next==null) { //先判断该链表是否无一个元素
this.next = newNode; //填入元素
cur = newNode; //将cur重新赋值
head = cur;
}else{
cur.next = newNode;
cur = newNode;
}
}
//将记录到最后节点的cur的next指向链表的头节点形成循环
cur.next = head;
return head;
}
该循环链表的创建与单链表的创建没有什么太大区别,最主要的区别就是链表的尾巴节点的next需要指向链表的头节点。
public void PrintList(){
LNode cur = this.next;
while(cur!=null){
System.out.print(cur.data+" ");
cur = cur.next;
}
System.out.println();
}
此外我还写了一个打印的函数PrintList。
代码实现看看链表是不是真的是循环的:
此时看到 打印的结果与我们想到的不太一样,可以正常打印说明循环条件出错了此时这个链表每一个next都有指向确切的值。所以while(cur!=null)这个条件会一直成立,此时我们可以使用dowhile循环来进行打印。
public void PrintList(){
if(this.next==null){
System.out.println("该链表为空");
return;
}
LNode head = this.next; //将链表的头节点记录下来
LNode cur = head; //定义一个cur
do{
System.out.print(cur.data+" ");
cur = cur.next;
}while(cur!=head); //当再次遇到头节点就结束了
}
这里起始还可以使用计数器进行打印。
循环链表的创建和打印操作都完成了。插入操作和删除操作其实都与单链表是差不多的这里就不说了,若是不熟悉的可以看我写的java实现单链表。
实现循环链表的查找确切位置的元素
public LNode getNode(int index){ LNode cur = this.next; //cur指向链表的第一个元素 int n =1; //用于计数 while(n<=index-1){ cur = cur.next; n++; } return cur; }
至此循环链表的基本操作都实现了
完整代码:
public class CircleLinkList {
public int data;
public LNode next;
public static class LNode{
public int data;
public LNode next;
public LNode(int value){
this.data = value;
this.next = null;
}
public void addNode(int val){
LNode newNode = new LNode(val);
if(this.next==null){
this.next = newNode;
}else {
LNode cur = this.next;
while(cur.next!=null){
cur = cur.next;
}
cur.next = newNode;
}
}
}
public void InitList(){ //初始化一个头节点
this.data = 0;
this.next = null;
}
public LNode CreateList(int n){
LNode cur=null;
LNode head =null;
for(int i=1;i<=n;i++){
LNode newNode = new LNode(i);
if(this.next==null) {
this.next = newNode;
cur = newNode;
head = cur;
}else{
cur.next = newNode;
cur = newNode;
}
}
cur.next = head;
return head;
}
public void PrintList(){
if(this.next==null){
System.out.println("该链表为空");
return;
}
LNode head = this.next;
LNode cur = head;
do{
System.out.print(cur.data+" ");
cur = cur.next;
}while(cur!=head);
}
public LNode getNode(int index){
LNode cur = this.next;
int n =1;
while(n<=index-1){
cur = cur.next;
n++;
}
return cur;
}
}
感谢您能看到这里,若是代码运行错误或是无法运行请留言