链表分为单项链表和双向链表,这里简单写了写,简单来说,就是通过修改链表指向关系来进行增删操作
public class MyLinkedList{ int size = 0; Node head; Node last; public MyLinkedList() { } public void add(T e) { Node l = last; Node tNode = new Node (e,null,l); last = tNode; if (l == null) { head = tNode; } else { l.next = tNode; } size++; } public void addFirst(T e) { Node f = head; Node tNode = new Node (e,f,null); head = tNode; if (f == null) { last = tNode; } else { f.prev = tNode; } size++; } public T get(int index) { if(index < 0 || index >= size){ throw new IndexOutOfBoundsException("数组越界:"+index); } if(index==0){ return head.data; }else{ Node node = last; for (int i = size - 1; i > index; i--) { node = node.prev; } return node.data; } } public void remove(int index){ if(index < 0 || index >= size){ throw new IndexOutOfBoundsException("数组越界:"+index); } Node node = last; for (int i = size - 1; i > index; i--) { node = node.prev; } node.prev.next=node.next; node.next.prev=node.prev; size--; } public void remove(T e){ if(e.equals(head.data)){ head=head.next; head.prev=null; size--; return; } Node temp = head; while (true){ //判断是否为最后一个 if(temp.next==null){ break; } //相等则移除 if(e.equals(temp.next.data)){ temp.next=temp.next.next; temp.next.next.prev=temp; size--; break; }else{ temp=temp.next; } } } public int size() { return size; } public void toPrint(){ for (int i=0; i System.out.print(get(i)+","); } } } class Node { T data; Node next; Node prev; public Node() { } public Node(T data, Node next, Node prev) { this.data = data; this.next = next; this.prev = prev; } }
测试类
public class Test {
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList<>();
list.add("张三");
list.add("李四");
list.add("王五");
list.add("赵六");
list.toPrint();
System.out.println();
System.out.println("======================= 分割线 =======================");
list.addFirst("赵四");
list.add("陈七");
list.toPrint();
System.out.println();
System.out.println("======================= 分割线 =======================");
list.remove("赵四");
list.remove(2);
list.toPrint();
}
}
测试结果
链表的结构是这样的



