链表
增
public void Insert(E data,int index){
if (index < 0 || index > length){
throw new IllegalArgumentException("插入位置不合法");
}
Node<E> prev = head;
while (index > 0){
prev = prev.next;
index--;
}
Node<E> newNode = new Node<>(data);
newNode.next = prev.next;
prev.next = newNode;
length++;
}
删
public E Delete(int index) {
if (index < 0 || index > length) {
throw new IllegalArgumentException("删除位置不合法");
}
Node<E> prev = head;
while (index > 0) {
prev = prev.next;
index--;
}
E data = prev.next.data;
prev.next = prev.next.next;
return data;
}
查
public E Get(int index) {
if (index < 0 || index > length) {
throw new IllegalArgumentException("获取位置不合法");
}
Node<E> cur = head.next;
while (index > 0) {
cur = cur.next;
index--;
}
return cur.data;
}
总览
package com.collection;
public class LinkList<E> {
private final Node<E> head = new Node<>(null);
private int length = 0;
private static class Node<E> {
private E data;
private Node<E> next;
public Node(E data) {
this.data = data;
}
}
public void Insert(E data,int index){
if (index < 0 || index > length){
throw new IllegalArgumentException("插入位置不合法");
}
Node<E> prev = head;
while (index > 0){
prev = prev.next;
index--;
}
Node<E> newNode = new Node<>(data);
newNode.next = prev.next;
prev.next = newNode;
length++;
}
public E Delete(int index) {
if (index < 0 || index > length) {
throw new IllegalArgumentException("删除位置不合法");
}
Node<E> prev = head;
while (index > 0) {
prev = prev.next;
index--;
}
E data = prev.next.data;
prev.next = prev.next.next;
return data;
}
public E Get(int index) {
if (index < 0 || index > length) {
throw new IllegalArgumentException("获取位置不合法");
}
Node<E> cur = head.next;
while (index > 0) {
cur = cur.next;
index--;
}
return cur.data;
}
@Override
public String toString() {
System.out.println("length = " + length);
StringBuilder builder = new StringBuilder();
Node<E> cur = head.next;
while (cur != null) {
builder.append(cur.data).append(" ");
cur = cur.next;
}
return builder.toString();
}
}
测试
package com.collection;
public class Main {
public static void main(String[] args) {
LinkList<Integer> linkList = new LinkList<>();
linkList.Insert(1, 0);
linkList.Insert(2,1);
linkList.Insert(3,2);
System.out.println(linkList);
linkList.Delete(0);
System.out.println(linkList);
System.out.println(linkList.Get(0));
}
}