Java函数创建和应用链表结构
发布时间:2023-07-09 22:45:17
链表是一种常见的数据结构,它由一系列节点组成,每个节点包含数据和指向下一个节点的指针。链表的优点是插入和删除操作的效率高,缺点是访问某个节点的效率较低。
在Java中,我们可以通过创建一个Node类来表示链表中的每个节点。Node类包含一个数据域(data)和一个指向下一个节点的引用(next)。
public class Node {
private int data;
private Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
public int getData() {
return data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
接下来,我们可以创建一个LinkedList类来管理链表。LinkedList类包含一个指向链表头节点的引用(head)。
public class LinkedList {
private Node head;
public LinkedList() {
this.head = null;
}
public boolean isEmpty() {
return head == null;
}
public void insert(int data) {
Node newNode = new Node(data);
if (isEmpty()) {
head = newNode;
} else {
Node current = head;
while (current.getNext() != null) {
current = current.getNext();
}
current.setNext(newNode); // 在链表末尾插入节点
}
}
public void delete(int data) {
if (isEmpty()) {
return;
}
if (head.getData() == data) {
head = head.getNext(); // 删除头节点
return;
}
Node current = head;
Node prev = null;
while (current != null && current.getData() != data) {
prev = current;
current = current.getNext();
}
if (current == null) {
return;
}
prev.setNext(current.getNext()); // 删除中间或末尾节点
}
public void display() {
if (isEmpty()) {
System.out.println("LinkedList is empty.");
return;
}
Node current = head;
while (current != null) {
System.out.print(current.getData() + " ");
current = current.getNext();
}
System.out.println();
}
}
现在,我们可以创建一个链表并进行操作。
public class Main {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.insert(1);
linkedList.insert(2);
linkedList.insert(3);
linkedList.insert(4);
linkedList.display(); // 输出:1 2 3 4
linkedList.delete(2);
linkedList.display(); // 输出:1 3 4
}
}
在上面的例子中,我们首先创建一个空LinkedList对象,然后向其中插入一些数据。然后,我们展示了如何删除数据并显示链表的内容。
以上就是使用Java创建和应用链表结构的基本过程。通过LinkedList类的插入和删除方法,我们可以方便地对链表进行操作。链表可以被用于解决很多实际问题,例如实现栈和队列,以及处理大量数据等。
