循环链表:
循环链表与单链表的区别仅仅在于其尾结点的链域值不是null,而是指向首节点节点的
作用。
public class Clink {
Node head;
public Clink() {
head=new Node();
head.next=null;
}
public void addNode(String data) {
/**
* 1.获取表头
* 2.通过表头找到最后一个元素
* 3.把新增的节点放到最后一个元素的后面
*/
Node p=head;
if(p.next==null) {
Node temp=new Node(data);
p.next=temp;
temp.next=head.next;
return;
}
p=p.next;
while(p.next!=head.next) {
p=p.next;
}
Node temp=new Node(data);
p.next=temp;
temp.next=head.next;
}
public void deleteNode(String data) {
/**
* 1.获取表头
* 2.通过表头找到最后一个元素
* 3.把最后一个元素删除
*/
Node p=head.next;
if(p.next==head.next) {
}
while(p.next!=head.next) {
if(p.next.id.equals(data)) {
p.next=p.next.next;
break;
}
else {
p=p.next;
}
}
}
public void display() {
Node p=head.next;
while(p.next!=head.next) {
System.out.println("->>"+p.id);
p=p.next;
}
System.out.println("->>"+p.id);
}
public void findNode(String data) {
/**
* 1.获取表头
* 2.通过表头找到该元素元素
* 3.把最后一个元素删除
*/
Node p=head.next;
while(p.next!=head.next) {
if(p.id.equals(data)) {
System.out.println(data+"要找的元素存在");
break;
}
else {
p=p.next;
}
}
if(p.id.equals(data)) {
System.out.println("data"+"要找的元素存在");
return;
}
}
public void insertNode(String param,String data) {
Node p=head.next;
while(p.next!=head.next) {
if(p.id.equals(param)) {
Node temp=p.next;
Node insertNode=new Node(data);
insertNode.next=temp;
p.next=insertNode;
break;
}else {
p=p.next;
}
}
if(p.next==head.next) {
Node temp=p.next;
Node insertNode=new Node(data);
insertNode.next=temp;
p.next=insertNode;
return;
}
}
public int size() {
Node p=head.next;
int n=1;
while(p.next!=head.next) {
p=p.next;
n++;
}
return n;
}
public static void main(String[] args) {
Clink link=new Clink();
link.addNode("组长");
link.addNode("部门经理");
link.addNode("主管副总");
link.addNode("总经理");
System.out.println("=================");
link.insertNode("总经理","董事长");
link.display();
System.out.println(link.size());
}
}