Java语言怎么在双向链表中实现冒泡法排序,排序的类型是Point类,怎么通过双向链表实现排序的比较的

Java语言怎么在双向链表中实现冒泡法排序,排序的类型是Point类,怎么通过双向链表实现排序的比较的。

这个有点复杂 我用多个类实现 先看效果图

img


目录结构如下 :

img

代码如下 :
Point类实现:

public class Point {
    private int x;
    private int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    @Override
    public String toString() {
        return "(" + x + ", " + y + ")";
    }
}

class Node {
    Point point;
    Node prev;
    Node next;

    public Node(Point point) {
        this.point = point;
    }
}

DoubleLinkedList 类实现 :

public class DoubleLinkedList {
    private Node head;
    private int size;

    public void add(Point point) {
        Node node = new Node(point);
        if (head == null) {
            head = node;
        } else {
            Node current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = node;
            node.prev = current;
        }
        size++;
    }

    public void display() {
        Node current = head;
        while (current != null) {
            System.out.print(current.point + " ");
            current = current.next;
        }
        System.out.println();
    }

    public void bubbleSort() {
        if (head == null || head.next == null) {
            return;
        }

        boolean swapped;
        do {
            swapped = false;
            Node current = head;
            while (current.next != null) {
                if (comparePoints(current.point, current.next.point) > 0) {
                    swap(current, current.next);
                    swapped = true;
                }
                current = current.next;
            }
        } while (swapped);
    }

    private int comparePoints(Point p1, Point p2) {
        return Integer.compare(p1.getX(), p2.getX());
    }

    private void swap(Node n1, Node n2) {
        Point temp = n1.point;
        n1.point = n2.point;
        n2.point = temp;
    }
}


Main 中

public class Main {
    public static void main(String[] args) {
        DoubleLinkedList list = new DoubleLinkedList();
        list.add(new Point(3, 8));
        list.add(new Point(1, 5));
        list.add(new Point(4, 2));
        list.add(new Point(2, 9));

        System.out.println("Original List:");
        list.display();

        list.bubbleSort();

        System.out.println("Sorted List:");
        list.display();
    }
}