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

实现链表操作的Java函数

发布时间:2023-12-12 09:12:25

链表是一种常用的数据结构,它由一系列节点组成,每个节点包含了数据和指向下一个节点的指针。链表操作包括插入节点、删除节点、查找节点等功能。

首先,我们需要定义一个链表节点类Node,包含数据data和指向下一个节点的指针next:

class Node {
    int data;
    Node next;
}

接下来,我们可以定义一个链表类LinkedList,用于封装链表的操作方法:

class LinkedList {
    private Node head;

    // 在链表头部插入节点
    public void insertAtHead(int data) {
        Node newNode = new Node();
        newNode.data = data;
        newNode.next = head;
        head = newNode;
    }

    // 在链表尾部插入节点
    public void insertAtTail(int data) {
        Node newNode = new Node();
        newNode.data = data;

        if (head == null) {
            head = newNode;
            return;
        }

        Node current = head;
        while (current.next != null) {
            current = current.next;
        }
        current.next = newNode;
    }

    // 删除指定节点
    public void deleteNode(int data) {
        if (head == null) {
            return;
        }

        if (head.data == data) {
            head = head.next;
            return;
        }

        Node current = head;
        Node previous = null;
        while (current != null && current.data != data) {
            previous = current;
            current = current.next;
        }

        if (current == null) {
            return;
        }

        previous.next = current.next;
    }

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

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

然后,我们可以在主函数中使用这个链表类来操作链表:

public class Main {
    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();

        // 在链表头部插入节点
        linkedList.insertAtHead(3);
        linkedList.insertAtHead(2);
        linkedList.insertAtHead(1);

        // 打印链表:1 2 3
        linkedList.printList();

        // 在链表尾部插入节点
        linkedList.insertAtTail(4);
        linkedList.insertAtTail(5);

        // 打印链表:1 2 3 4 5
        linkedList.printList();

        // 删除节点
        linkedList.deleteNode(3);

        // 打印链表:1 2 4 5
        linkedList.printList();

        // 查找节点
        System.out.println(linkedList.searchNode(4)); // true
        System.out.println(linkedList.searchNode(6)); // false
    }
}

通过上述代码,我们可以实现链表的插入、删除、查找等操作。在实际应用中,链表常用于需要频繁插入和删除节点的场景,因为链表的插入和删除操作相对比较高效。