常见的链表有单向链表、双向链表、循环链表;现在依次给予实现,具体文字以后描述慢慢写
1、单向链表
package com.ccy.struct;
public class LinkList<T> {
/** 节点 */
private class Node {
private T data;
private Node next;
public Node(T data, Node next) {
this.data = data;
this.next = next;
}
}
private Node header; // 头结点
private Node tail; // 尾结点
private int size;
public LinkList() {
header = null;
tail = null;
}
public int length() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
/** 增加 */
public LinkList<T> add(T element) {
if (header == null) { // 空链表
header = new Node(element, null);
tail = header;
} else { // 非空链表
Node newNode = new Node(element, null);
tail.next = newNode;
tail = newNode;
}
size++;
return this;
}
private Node getNodeByIndex(int index) {
if (index < 0 || index > size - 1) {
throw new IndexOutOfBoundsException("索引越界");
}
Node currentNode = header;
for (int i = 0; i < size && currentNode != null; i++, currentNode = currentNode.next) {
if (i == index) {
return currentNode;
}
}
return null;
}
public T delete(int index) {
if (index < 0 || index > size - 1) {
throw new IndexOutOfBoundsException("索引越界");
}
Node del = null;
if (index == 0) {
del = header;
header = header.next;
} else {
Node prev = getNodeByIndex(index - 1);
del = prev.next;
prev.next = del.next;
del.next = null;
}
size--;
return del.data;
}
public void clean() {
header = null;
tail = null;
size = 0;
}
public String toString() {
if (isEmpty()) {
return "[]";
} else {
StringBuffer sb = new StringBuffer("[");
for (Node currentNode = header; currentNode != null; currentNode = currentNode.next) {
sb.append(currentNode.data.toString() + ", ");
}
int len = sb.length();
return sb.delete(len - 2, len).append("]").toString();
}
}
}
测试类
public class App {
public static void main(String[] args) {
LinkList<String> list = new LinkList<String>();
list.add("ccy")
.add("xfh")
.add("yk");
System.out.println(list.toString()); // [ccy, xfh, yk]
}
}