自己靠感觉实现的一个单向循环链表,写的代码很low~~~
public class Josephu {
public static void main(String[] args) {
SingleCircleLinkedList list = new SingleCircleLinkedList();
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(4);
Node node5 = new Node(5);
Node node6 = new Node(6);
Node node7 = new Node(7);
Node node8 = new Node(8);
list.add(node1);
list.add(node2);
list.add(node3);
list.add(node4);
list.add(node5);
list.add(node6);
list.add(node7);
list.add(node8);
list.show();
System.out.println("删除节点========");
list.delete(2);
list.delete(7);
list.show();
System.out.println("删除尾节点======");
list.delete(8);
list.show();
System.out.println("删除头节点======");
list.delete(1);
list.show();
System.out.println("################");
list.delete(3);
list.delete(4);
list.delete(5);
list.delete(6);
list.delete(6);
list.show();
}
}
class SingleCircleLinkedList {
private Node first;
public SingleCircleLinkedList() {
first = new Node(-1);
}
public void add(Node newNode) {
//添加的第一个节点,自己指向自己
if (first.next == null) {
first = newNode;
newNode.next = first;
return;
}
Node cur = first;
while (cur.next != first) {
cur = cur.next;
}
//添加新的节点到末尾,并指向第一个节点
cur.next = newNode;
newNode.next = first;
}
public void delete(int num) {
//判断循环链表是否为空
if (isEmpty()) {
System.out.println("链表为空~");
return;
}
//判断是否是最后一个节点
if (first == first.next) {
first.next = null;
return;
}
Node cur = first;
//用于记录删除节点的上一个节点
Node temp = null;
while (cur.num != num) {
temp = cur;
cur = cur.next;
}
//判断删除的节点是否是第一个节点,是则让下一个节点作为第一个节点
if (cur == first) {
Node lastNode = getLastNode();
first = first.next;
lastNode.next = first;
return;
}
//所要删除节点的上一个节点指向删除节点的下一个节点
temp.next = cur.next;
}
/**
* 获取循环链表的最后一个节点
*
* @return
*/
public Node getLastNode() {
if (isEmpty()) {
System.out.println("链表为空~");
}
Node cur = first;
while (cur.next != first) {
cur = cur.next;
}
return cur;
}
/**
* 判断链表是否为空
*/
public boolean isEmpty() {
if (first.next == null) {
return true;
}
return false;
}
/**
* 遍历展示链表中所有的元素
*/
public void show() {
if (isEmpty()) {
System.out.println("链表为空~");
return;
}
Node cur = first;
while (cur.next != first) {
System.out.println(cur);
cur = cur.next;
}
System.out.println(cur);
}
/**
* 获取链表的长度
*
* @return
*/
public int size() {
Node cur = first;
int count = 0;
while (cur.next != first) {
count++;
cur = cur.next;
}
return count;
}
}
class Node {
public int num;
public Node next;
public Node(int num) {
this.num = num;
}
@Override
public String toString() {
return "Node{" +
"num=" + num +
'}';
}
}