# 手写单链表结构

·  阅读 50

``````public class MyLinkList {
private Node last;
private int size;
}

``````public class Node {
private int data;
private Node next;
public Node(int data) {
this.data = data;
}
}

`````` public void insertData(int data, int index) throws Exception {

Node insertNode = new Node(data);

if (index > size) {
throw new Exception("index 应该小于size");
}
if (size == 0) {//创建链表  为空
last = insertNode;
} else if (index == 0) {
} else if (index == size) {//插入尾部
last.next = insertNode;//原来的last 变成倒数第二个  next 指向insertNode
last = insertNode; // 重置last  执行新的insertNode
} else {
//中间插入
Node pre = getNode(index - 1);//获取需要插入的node 前一个node
insertNode.next = pre.next;  // 需要插入的node next 等于原来链表位置的node 的下一个node
pre.next = insertNode;//原来的node next 指向插入的node;
}
size++;

}

``````private Node getNode(int index) throws Exception {
if (index < 0 || index > size) {
throw new Exception("index 下标越界");
}
for (int i = 0; i < index; i++) {
temp = temp.next;
}
return temp;

}

``````public void deleteNode(int index) throws Exception {
if (size == 0 || index <= 0 || index > size) {
throw new Exception("下标越界");
}
if (index == 0) {
//从头删除
} else if (index == size - 1) {
Node node = getNode(index - 1);//得到尾部上一个节点
node.next = null;
last = node;//上一个节点置为 last;
} else {
// 从中间删除
Node pre = getNode(index - 1);//得到尾部上一个节点
pre.next = pre.next.next;  //前一个节点的下下一个节点是需要连接的节点;

}
size--;
}

``````
/**
* 打印链表.
*/
public void print() {
if (size <= 0) {
throw new IndexOutOfBoundsException("数据为空！");
}
StringBuffer sb = new StringBuffer();
sb.append(temp.data);
for (int i = 0; i < size; i++) {
if (temp.next != null) {
temp = temp.next;
sb.append("===>" + temp.data);
}
}
System.out.println("temp.data" + sb.toString());
}

``````public static void main(String[] args) {
try {
} catch (Exception e) {
e.printStackTrace();
}
}

``````temp.data2
temp.data2===>3
temp.data4===>2===>3
temp.data4===>2===>3===>5
temp.data4===>2===>3===>5===>45
temp.data4===>2===>3===>67===>5===>45
temp.data4===>63===>2===>3===>67===>5===>45
temp.data4===>63===>2===>3===>67===>45

Android

Android