前言
前面我们对单链表的表头进行数据的插入和删除,其实也就是实现栈的链式存储。然而仅仅对首个结点进行操作太 easy,我们需要的是对任意位置的查询和删除。
目录
- 查询结点
- 删除任意结点
查询结点
以结点中存储的值为查询的索引
//根据值查询链表
private List queryByKey(int key) {
List current = first;
while (current.data != key) {
if (current.next == null) {
return null;
} else {
current = current.next;
}
}
return current;
}
删除任意结点
和查询结点相似,删除节点需要对链表进行遍历。但删除一个结点需要获取当前结点和前一结点,所有需要两个指针。
// 删除指定的结点
public void deleteByKey(int key) {
List current = first;
List previous = first;
while (current.getData() != key) {
if (current.next == null) {
return;
} else {
previous = current;
current = current.next;
}
}
// 此时找到了
if (current == first) {
first = first.next;
} else {
System.out.println("删除" + current.getData());
previous.next = current.next;
}
}
详细代码
// 单链表
// author Ethan
import java.util.Scanner;
public class LinkList {
// 头结点
public List first;
public LinkList() {
first = null;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int key;
LinkList linkList = new LinkList();
//插入数据
linkList.insertFirst(1);
linkList.insertFirst(3);
linkList.insertFirst(5);
linkList.insertFirst(10);
linkList.insertFirst(23);
linkList.insertFirst(35);
//打印
linkList.displayAll();
System.out.println("/");
//删除头结点
linkList.deleteFirst();
linkList.displayAll();
//根据节点中数据删除特定的结点
key = in.nextInt();
linkList.deleteByKey(key);
System.out.println("/");
linkList.displayAll();
}
public boolean isEmpty() {
if (first == null) {
return true;
} else
return false;
}
//头部插入节点
public void insertFirst(int data) {
List listNode = new List(data);
listNode.next = first;
first = listNode;
}
//删除节点
public void deleteFirst() {
first = first.next;
}
// 删除指定的结点
public void deleteByKey(int key) {
List current = first;
List previous = first;
while (current.getData() != key) {
if (current.next == null) {
return;
} else {
previous = current;
current = current.next;
}
}
// 此时找到了
if (current == first) {
first = first.next;
} else {
System.out.println("删除" + current.getData());
previous.next = current.next;
}
}
//遍历节点
public void displayAll() {
if (isEmpty()) {
System.out.println("空链表");
} else {
for (List node = first; node != null; node = node.next) {
System.out.println(node.getData());
}
}
}
//根据值查询链表
private List queryByKey(int key) {
List current = first;
while (current.data != key) {
if (current.next == null) {
return null;
} else {
current = current.next;
}
}
return current;
}
// 链表的节点
class List {
private int data;
private List next;
public List(int data) {
this.data = data;
}
public int getData() {
return data;
}
}
}