概述
链表是由一个一个的节点组成,第一个节点叫首节点,最后一个节点叫末节点,每个节点中都存放着数据。单向链表中每个节点通过next的指针指向下一个节点,末节点的next指针指向null。
Java中可以通过两个类来定义单向链表,一个是节点类,一个是链表类。
节点类中定义节点数据,指向下一个节点的指针,提供读取/更改以上两个数据的方法。每一个节点对象的next都是下一个节点本身。
链表类中定义整个链表,提供增删改查方法。
代码实现
public class LinkedListZ<E> {
private class Node {
public E e;
public Node next;
public Node(E e, Node next) {
this.e = e;
this.next = next;
}
public Node(E e) {
this(e, null);
}
public Node() {
this(null, null);
}
@Override
public String toString() {
return e.toString();
}
}
private Node dummyHead;
private Node Last;
private int size;
public LinkedListZ() {
dummyHead = new Node(null, null);
size = 0;
}
//获取元素个数
public int getSize() {
return size;
}
//是否为空
public boolean isEmpty() {
return size == 0;
}
//在链表首部添加元素
public void addFirst(E e) {
add(0, e);
}
//在链表的index位置添加节点
public void add(int index, E e) {
if (index < 0 || index > size) {
throw new IllegalArgumentException("Add failed, index illegal");
}
Node pre = dummyHead;
for (int i = 0; i < index; i++) {
pre = pre.next;
}
pre.next = new Node(e, pre.next);
size++;
}
//末尾添加元素
public void addLast(E e) {
add(size, e);
}
//获取index索引的数
public E getIndex(int index) {
if (index < 0 || index > size) {
throw new IllegalArgumentException("Add failed, index illegal");
}
Node cur = dummyHead.next;
for (int i = 0; i < index; i++) {
cur = cur.next;
}
return cur.e;
}
//获取链表首位数
public E getFirst() {
return getIndex(0);
}
//获取链表末位数
public E getLast() {
return getIndex(size - 1);
}
//改变index索引上的值
public void set(int index, E e) {
if (index < 0 || index >= size) {
throw new IllegalArgumentException("Add failed, index illegal");
}
Node cur = dummyHead.next;
for (int i = 0; i < index; i++) {
cur = cur.next;
}
cur.e = e;
}
//链表上是否存在元素e
public boolean contains(E e) {
Node cur = dummyHead.next;
while (cur != null) {
if (cur.e == e) {
return true;
}
cur = cur.next;
}
return false;
}
//移除链表中索引为index的元素
public E remove(int index) {
if (index < 0 || index >= size) {
throw new IllegalArgumentException("Add failed, index illegal");
}
Node pre = dummyHead;
for (int i = 0; i < index; i++) {
pre = pre.next;
}
Node cur = pre.next;
pre.next = cur.next;
cur.next = null;
size--;
return cur.e;
}
public E removeFirst() {
return remove(0);
}
public E removeLast() {
return remove(size - 1);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Node cur = dummyHead.next;
while (cur != null) {
sb.append(cur + "->");
cur = cur.next;
}
sb.append("Null");
return sb.toString();
}
}
测试用代码
public static void main(String[] args) {
LinkedListZ<Integer> linkedList = new LinkedListZ<Integer>();
for(int i = 0 ; i < 5 ; i ++){
linkedList.addFirst(i);
System.out.println(linkedList);
}
linkedList.add(2, 666);
System.out.println(linkedList);
linkedList.remove(2);
System.out.println(linkedList);
linkedList.removeFirst();
System.out.println(linkedList);
linkedList.removeLast();
System.out.println(linkedList);
}