该链表使用java编写实现了基础功能的单向链表。
附代码:
代码包括了一个内部节点类。
/**
* @author Grant
*
* @param <E>
*/
public class LinkedList<E> {
// 头节点
private Node top;
// 链表长度
private int size;
// 添加方法
public void add(E e) {
Node newNode = new Node();
newNode.content = e;
if (top == null) {
top = newNode;
} else {
this.top.addNewNode(newNode);
}
size++;
}
// 插入方法
public void add(int index, E e) {
Node newNode = new Node();
newNode.content = e;
if (index == 0) {
newNode.next = top;
top = newNode;
size++;
return;
}
this.top.addNewNode(index, newNode);
size++;
}
// 修改方法
public void set(int index, E e) {
Node newNode = new Node();
newNode.content = e;
this.top.alterNode(index, newNode);
}
// 删除方法
public boolean delete(int index) {
boolean flag = false;
if (index == 0) {
top = top.next;
size--;
flag = true;
} else {
flag = top.deleteNode(index);
}
if (flag = true) {
size--;
}
return flag;
}
// 重写toString方法
@Override
public String toString() {
return "LinkedList [top=" + top + ", size=" + size + "]";
}
// 获取最后一个元素
public E get() {
E msg = null;
if (top == null) {
return null;
} else {
msg = (E)top.get();
}
return msg;
}
// 获取指定元素
public Object get(int index) {
Object msg = top.get(index);
return msg;
}
// 获取链表长度方法
public int size() {
return size;
}
/**
* @author Grant 内部类:节点
*/
private class Node {
// 链表节点内容
Object content;
// 链表下一节点
Node next;
// 判断下一节点是否为空
public boolean nextIsnull() {
if (next == null) {
return true;
} else {
return false;
}
}
// 重写toString方法
@Override
public String toString() {
return "Node [content=" + content + ", next=" + next + "]";
}
// 在链表末端添加一个新节点
public void addNewNode(Node newNode) {
if (!nextIsnull()) {
this.next.addNewNode(newNode);
} else {
this.next = newNode;
}
}
// 在指定位置插入一个节点
public void addNewNode(int index, Node newNode) {
if (index > 1) {
index--;
this.next.addNewNode(index, newNode);
} else {
if (!this.nextIsnull()) {
newNode.next = this.next;
this.next = newNode;
} else {
this.next = newNode;
}
}
}
// 修改指定的一个节点的节点内容
public void alterNode(int index, Node newNode) {
if (index > 0) {
index--;
this.next.alterNode(index, newNode);
} else {
Node temp = null;
if (!this.nextIsnull()) {
temp = this.next;
if (!this.next.nextIsnull()) {
temp = this.next;
}
}
this.content = newNode.content;
this.next = temp;
}
}
// 获取最后一个节点内容
public Object get() {
Object temp = null;
if (this.nextIsnull()) {
temp = content;
return temp;
} else {
temp = this.next.get();
return temp;
}
}
// 删除指定位置节点
public boolean deleteNode(int index) {
boolean flag = false;
if (index > 1) {
index--;
flag = this.next.deleteNode(index);
} else {
if (!this.next.nextIsnull()) {
this.next = this.next.next;
flag = true;
} else {
this.next = null;
flag = true;
}
}
return flag;
}
// 获取指定的节点内容
public Object get(int index) {
Object temp = null;
if (index > 0) {
index--;
temp = this.next.get(index);
return temp;
} else {
temp = content;
return temp;
}
}
}
}