环形链表:所谓环形链表通俗的来说就是一个结点可以通过若干次遍历之后,又可以 遍历到自身。
环形链表的创建思路:
考虑到所有的结点加入进链表都要成环,则将第一个结点特殊化,每次将新的结点加进来都指向第一个结点,每次都断开上一个结点指向第一个结点的指针。这样保证链表成为一个尾指向头的环形链表。
我们将用到三个指针:
第一个firstNode指针,永远都指向第一个结点。
第二个指针curNode,指向链表的最后一个结点。
第三个就是指向当前加进来结点的指针heroNode。
在对第一个结点进行操作时(第一个结点有且仅需要操作一次)
firstNode = heroNode;
firstNode.next = firstNode;
curNode = firstNode;
flag = 0;
先将firstNode指针指向当前的Heronode
再使firstNode的next也指向firstNode,成环。
最后将curNode指向当前的结点,也就是firstNode
若有新的结点进来时(之后的操作都是对新结点进行操作):
curNode.next=heroNode;
heroNode.next=firstNode;
curNode=heroNode;
curNode是指向第一个结点的,我们将curNode指向新进来的结点,则结点一的环就断开了。
再将heroNode也就是指向当前节点的指针指向firstNode,则尾和firstNode就成了环。
最后将curNode指向此时链表的最后一个结点,也就是heroNode。
每次有新的结点进来时都进行以上操作,注意:第一个节点有且仅需要操作一次
package datastructure01.circularlinkedlist;
public class CirclularLinkedListDemo {
public static void main(String[] args) {
HeroNode heroNode1 = new HeroNode(1, "zz");
HeroNode heroNode2 = new HeroNode(2, "xx");
HeroNode heroNode3 = new HeroNode(3, "aa");
HeroNode heroNode4 = new HeroNode(4, "ss");
CirclularLinkedList cl = new CirclularLinkedList();
cl.add(heroNode1);
cl.add(heroNode2);
cl.add(heroNode3);
cl.add(heroNode4);
cl.select();
System.out.println("-------------");
}
}
class CirclularLinkedList {
HeroNode firstNode = null;
HeroNode curNode = null;
int flag = 1;
public void add(HeroNode heroNode) {
if (flag == 1) {
firstNode = heroNode;
firstNode.next = firstNode;
curNode = firstNode;
flag = 0;
} else {
curNode.next=heroNode;
heroNode.next=firstNode;
curNode=heroNode;
}
}
public void select() {
HeroNode temp=firstNode;
while (true){
System.out.println(temp);
if(temp.next==firstNode){
break;
}
else {
temp=temp.next;
}
}
}
}
class HeroNode {
private int num;
private String name;
HeroNode next;
public HeroNode(int num, String name) {
this.num = num;
this.name = name;
}
@Override
public String toString() {
return "HeroNode{" +
"num=" + num +
", name='" + name + '\'' +
'}';
}
}