Java

java有序链表的实际案例分析

小樊
84
2024-09-14 07:38:09
栏目: 编程语言

在Java中,有序链表通常是指一个已经按照特定顺序(如升序或降序)排列的链表。这种数据结构在插入、删除和查找操作时非常高效。以下是一个简单的有序链表实现示例:

  1. 首先,我们需要创建一个节点类(Node)来表示链表中的每个元素:
class Node {
    int data;
    Node next;

    public Node(int data) {
        this.data = data;
        this.next = null;
    }
}
  1. 接下来,我们创建一个有序链表类(SortedLinkedList)并实现基本的操作方法,如插入、删除和查找:
class SortedLinkedList {
    Node head;

    public void insert(int data) {
        Node newNode = new Node(data);

        if (head == null || head.data >= data) {
            newNode.next = head;
            head = newNode;
        } else {
            Node current = head;
            while (current.next != null && current.next.data< data) {
                current = current.next;
            }
            newNode.next = current.next;
            current.next = newNode;
        }
    }

    public void delete(int data) {
        if (head == null) return;

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

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

        if (current.next != null) {
            current.next = current.next.next;
        }
    }

    public boolean search(int data) {
        Node current = head;
        while (current != null) {
            if (current.data == data) {
                return true;
            }
            if (current.data > data) {
                break;
            }
            current = current.next;
        }
        return false;
    }
}
  1. 最后,我们可以创建一个主类(Main)来测试我们的有序链表实现:
public class Main {
    public static void main(String[] args) {
        SortedLinkedList list = new SortedLinkedList();

        list.insert(5);
        list.insert(3);
        list.insert(7);
        list.insert(1);

        System.out.println("Searching for 3: " + list.search(3)); // 输出:Searching for 3: true
        System.out.println("Searching for 4: " + list.search(4)); // 输出:Searching for 4: false

        list.delete(3);
        System.out.println("Searching for 3 after deletion: " + list.search(3)); // 输出:Searching for 3 after deletion: false
    }
}

这个简单的有序链表实现展示了如何在Java中创建和操作有序链表。在实际应用中,你可能需要根据具体需求对这个实现进行扩展和优化。

0
看了该问题的人还看了