链表(List)是一种经常使用的一种基本数据结构。基本原理如下图片所示:
以下使用Java代码实现了包括添加、删除和插入在内的基本操作。
/**
* 自定义整型链表,包括了添加、删除和插入等操作。
* @author Wei HAO
* Date: 2019/04/15
*
*/
public class IntegerList {
public static void main(String[] args) {
IntegerList ln1 = new IntegerList(1);
ln1.addLast(5);
ln1.addLast(4);
ln1.insert(1, 10);
ln1.delete(2);
IntegerList.print(ln1);
}
public int data; // the main content of the node
public IntegerList next; // the pointer to the next node
public IntegerList last; // the last node of the current list.
/**
* Inserts an element into the specified position.
* @param position
* @param data
*/
public void insert(int position, int data) {
IntegerList p = this;
for(int i = 0; i < position - 1; i++)
p = p.next;
IntegerList ln = new IntegerList(data);
ln.next = p.next;
p.next = ln;
if(p == last)
last = ln;
}
/**
* Append a new node with given data to the tail of the list.
* @param data The data of a list node.
*/
public void addLast(int data) {
last = last.add(data);
}
/**
* add a new node to the current node with the given data.
* @param data
* @return
*/
private IntegerList add(int data) {
IntegerList ln = new IntegerList(data);
this.next = ln;
last = ln;
return ln;
}
/**
* Deletes the element at position.
* @param position
* @return
*/
public int delete(int position) {
IntegerList p = this;
for(int i = 0; i < position - 1; i++)
p = p.next;
int value = p.next.data;
p.next = p.next.next;
return value;
}
/**
* A constructor with no argument.
*/
public IntegerList() {
last = this;
}
/**
* A constructor with one argument of integer.
* @param data The main content of the node.
*/
public IntegerList(int data) {
this.data = data;
last = this;
}
/**
* Print all the data of all the nodes of the list.
* @param ln
*/
public static void print(IntegerList ln) {
IntegerList p = ln;
do {
System.out.print(p.data + " ");
p = p.next;
} while (p != null);
}
/**
* Returns the number of nodes of the current list.
* @return
*/
public int size() {
IntegerList p = this;
int size = 0;
do {
size ++;
p = p.next;
} while (p != null);
return size;
}
}
[1] 链表图片,百度百科,https://baike.baidu.com/item/链表/9794473?fr=aladdin