储存结构定义:
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
struct Node{
ElemType Element;
Position Next;
};
代码书写:
package theDataStructureAboutLinked;
/**
* 该类用于充当连表节点
*/
public class Node {
// 存储的数据
public String data;
// 下一个节点
public Node nextNode;
// 当这个节点是节点头时
static public Node head = new Node();
public Node() {
}
// 构造方法——存储数值
public Node(String data) {
this.data = data;
}
// 计算该链表的长度
public int length() {
int length = 0;
Node temp = head;
while (temp.nextNode != null) {
length++;
temp = temp.nextNode;
}
return length;
}
// 添加节点
public void addNode(Node data) {
Node temp = head;
while (temp.nextNode != null) {
temp = temp.nextNode;
}
temp.nextNode = data;
}
// 插入节点
public void insertNode(int index, Node data) {
// 首先判断传入参数是否有误
if (index < 1 || index > length()) {
return;
}
Node temp = head;
int length = 0;
// 找到相对应下标数值
while (temp.nextNode != null) {
if (index == length++) {
data.nextNode = temp.nextNode;
temp.nextNode = data;
return;
}
temp = temp.nextNode;
}
}
// 删除节点
public void deleteNode(int index) {
// 首先判断传入参数是否有误
if (index < 1 || index > length()) {
return;
}
// 设置开头值
Node temp = head;
// 设置长度
int length = 0;
// 找到该下标点
while (temp.nextNode != null) {
if (index == length++) {
temp.nextNode = temp.nextNode.nextNode;
return;
}
temp = temp.nextNode;
}
}
// 打印
public void show() {
Node a = head.nextNode;
while (a != null) {
System.out.println(a.data);
a = a.nextNode;
}
}
}