链表(Linked list)是一种常见的基础数据结构,在开发中扮演了重要的角色,下面给出链表的编写。
下面给出节点的编写以及链表的插入、删除以及遍历,下面是代码
/**
*链表
-
author 徐静远
*/
public class MyLinkedList {
//创建size用于存储节点的个数
int size;
//创建一个头节点
Node head;//插入方法
public void insert(int index, String data) {
//要插入的下标比链表的后一位还大时
if (size < index) {
return;
}
//链表为空时
if (size == 0) {
Node node = new Node(data);
head = node;
size++;
//插入链表最前面时
} else if (index == 0) {
Node node = new Node(data);
node.next = head;
head = node;
size++;
//插入链表最后时
} else if (size == index) {
Node node = head;
for (int i = 0; i < size - 1; i++) {
node = node.next;
}
Node node1 = new Node(data);
node.next = node1;
size++;
//插入链表中间时
} else {
Node previous = head;
Node after = head;
for (int i = 0; i < index - 1; i++) {
previous = head.next;
}
for (int i = 0; i < index; i++) {
after = head.next;
}
Node node1 = new Node(data);
previous.next = node1;
node1.next = after;
size++;
}}
//删除方法
public boolean delete(int index) {
//删除的下标异常时
if (index < 0 || index > size - 1) {
return false;
//删除链表头时
} else if (index == 0) {
head = head.next;
size–;
return true;
//删除链表尾时
} else if (index == size - 1) {
Node node = head;
for (int i = 0; i < size - 1; i++) {
node = node.next;
}
node.next = null;
size–;
//删除链表中间时
} else {
Node previous = head;
for (int i = 0; i < index - 1; i++) {
previous = previous.next;
}
Node after = previous.next.next;
previous.next = after;
size–;
return true;
}
return true;
}//遍历
public void show() {
Node node = head;
for (int i = 0; i < size; i++) {
System.out.println(node);
node = node.next;
}
}
}
//创建一个节点类
class Node {
//要存储的数据
String data;
//构造方法
public Node(String data) {
this.data = data;
}
//创建next用于存储下一个节点的地址
Node next;
@Override
public String toString() {
return "Node{" +
"data='" + data + '\'' +
", next=" + next +
'}';
}
}