欢迎访问宙启技术站
智能推送

如何使用Java实现链表的增删查改操作?

发布时间:2023-07-01 16:37:54

链表是一种常见的数据结构,它由一系列节点组成,每个节点包含两部分:数据部分和指针部分。数据部分用于存储具体的数据,指针部分用于指向下一个节点。

在Java中,可以通过定义一个Node类来实现链表的增删查改操作。Node类包含一个数据域和一个指针域,通过指针域可以连接多个节点形成链表。

首先,定义一个Node类:

public class Node {
    public int data;  // 数据域
    public Node next;  // 指针域

    public Node(int data) {
        this.data = data;
        this.next = null;
    }
}

接下来,定义一个LinkedList类来管理链表:

public class LinkedList {
    private Node head;  // 头节点

    public LinkedList() {
        this.head = null;
    }

    // 增加节点
    public void addNode(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
        } else {
            Node temp = head;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = newNode;
        }
    }

    // 删除节点
    public void deleteNode(int data) {
        if (head == null) {
            return;
        }
        if (head.data == data) {
            head = head.next;
            return;
        }
        Node temp = head;
        while (temp.next != null && temp.next.data != data) {
            temp = temp.next;
        }
        if (temp.next != null) {
            temp.next = temp.next.next;
        }
    }

    // 查找节点
    public boolean searchNode(int data) {
        Node temp = head;
        while (temp != null) {
            if (temp.data == data) {
                return true;
            }
            temp = temp.next;
        }
        return false;
    }

    // 修改节点
    public void modifyNode(int oldData, int newData) {
        Node temp = head;
        while (temp != null) {
            if (temp.data == oldData) {
                temp.data = newData;
                return;
            }
            temp = temp.next;
        }
    }

    // 打印链表
    public void printLinkedList(){
        Node temp = head;
        while(temp != null){
            System.out.print(temp.data+" ");
            temp = temp.next;
        }
        System.out.println();
    }
}

在main函数中可以通过调用LinkedList类的方法来增删查改链表:

public class Main {
    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();
        
        linkedList.addNode(1);
        linkedList.addNode(2);
        linkedList.addNode(3);
        linkedList.addNode(4);
      
        linkedList.printLinkedList();  // 打印链表: 1 2 3 4

        linkedList.deleteNode(3);      
        linkedList.printLinkedList();  // 打印链表: 1 2 4

        System.out.println(linkedList.searchNode(2));  // 查找节点: true

        linkedList.modifyNode(2, 5);      
        linkedList.printLinkedList();  // 打印链表: 1 5 4
    }
}

这样,就实现了一个简单的链表的增删查改操作。可以根据实际需求对链表进行扩展,实现更复杂的功能。