public class RecycleLinkedList {
@Test
public void test() {
System.out.println("00000000000000000000000000000000");
RecycleLinkList recycleLinkList = new RecycleLinkList();
System.out.println("添加值以后的大小:" + recycleLinkList.add(5));
System.out.println("添加值以后的大小:" + recycleLinkList.add(6));
System.out.println("添加值以后的大小:" + recycleLinkList.add(7));
System.out.println("添加值以后的大小:" + recycleLinkList.add(908));
recycleLinkList.show();
System.out.println("00000000000000000000000000000000");
System.out.println("删除下标为x的值以后的大小:"+recycleLinkList.delete(3));
recycleLinkList.show();
System.out.println("00000000000000000000000000000000");
}
class Node {
int data;
Node next = null;
private Node() {
}
Node(int data) {
this.data = data;
}
}
class RecycleLinkList {
//预置两个结点,少于两个节点不能结点
Node head = null;
Node first = null;
//记录链表大小
int size = 0;
public int add(int data) {
Node temp = new Node(data);
//头结点赋值
if (head == null) {
head = temp;
return ++size;
}
//first结点赋值
if (first == null) {
first = temp;
head.next = first;
first.next = head;
return ++size;
}
Node current = head;
for (int i = 1; i < size; i++) {
current = current.next;
}
temp.next = head;
current.next = temp;
return ++size;
}
public int delete(int index) {
if (index >= size) {
System.out.println("链表没有那么大哦");
return 0;
}
Node pre = head;
//获取到要删除结点的前一个结点
for (int i = 0; i < index - 1; i++) {
pre = pre.next;
}
// Node current = pre.next;
pre.next = pre.next.next;
return --size;
}
public void show() {
if (size < 1) {
System.out.println("现在是空链表");
}
Node current = head;
for (int i = 0; i < size; i++) {
System.out.println(current.data);
current = current.next;
}
}
}
}