Java 单链表负整数排序算法:高效移动负数到列表前
以下是一个 Java 代码设计的示例,其中包含了单链表的相关操作方法以及将负整数移动到其他元素前面的算法:
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
public LinkedList() {
this.head = null;
}
// 在链表末尾添加元素
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
// 将所有负整数的元素移动到其他元素前面
public void moveNegativeNumbers() {
if (head == null || head.next == null) {
return;
}
Node prev = null;
Node current = head;
while (current != null && current.data < 0) {
head = current.next;
current.next = prev;
prev = current;
current = head;
}
if (current == null) {
head = prev;
return;
}
Node negativePrev = prev;
Node negativeCurrent = current;
while (current != null) {
if (current.data < 0) {
negativePrev.next = current.next;
current.next = negativeCurrent;
if (prev == null) {
head = current;
} else {
prev.next = current;
}
prev = current;
current = negativePrev.next;
} else {
negativePrev = current;
current = current.next;
}
}
}
// 打印链表元素
public void display() {
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 list = new LinkedList();
list.add(1);
list.add(2);
list.add(-1);
list.add(-2);
list.add(3);
list.add(-3);
list.add(4);
System.out.print("原始链表:");
list.display();
list.moveNegativeNumbers();
System.out.print("移动后的链表:");
list.display();
}
}
运行以上代码,输出如下:
原始链表:1 2 -1 -2 3 -3 4
移动后的链表:-1 -2 -3 1 2 3 4
这个示例中,我们首先定义了一个Node类来表示链表中的节点,节点包含一个整数类型的data属性和一个指向下一个节点的next引用。然后定义了一个LinkedList类来表示链表,包含了添加元素、将负整数移动到其他元素前面以及打印链表元素的方法。最后,通过在Main类中创建一个LinkedList对象,并添加一些测试数据来测试链表的功能。
原文地址: https://www.cveoy.top/t/topic/pgWi 著作权归作者所有。请勿转载和采集!