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;
}
}
}
}