【发布时间】:2019-05-05 09:31:40
【问题描述】:
我试图创建一种算法,将一些元素放入链接列表,然后使用冒泡排序将这些元素传递到数组中以对元素进行排序。我对这些元素进行了排序,但现在我无法再次将数组中的元素传递到链接列表。
我使用passIntoArray(Node head, int arr[]) 方法从链接列表中获取元素并传递到数组中。方法count(Node head) 用于检查链接列表中有多少元素(当前用作数组的索引)。谁能帮帮我?
package LinkedList;
public class LinkedListSorting {
private static int count(Node head) {
if (head == null) return 0;
Node current = head;
int count = 0;
while(current != null) {
count++;
current = current.next;
} return count;
}
private static void passIntoArray(Node head, int arr[]) {
if (head == null) return;
Node current = head;
int i = 0;
while(current != null) {
arr[i] = current.data;
i++;
current = current.next;
}
int length = count(head);
for(i=0; i<length; i++) {
for(int j=i+1; j<length; j++) {
if(arr[i]>arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(i=0; i<length; i++) {
System.out.println(arr[i]);
}
}
//FROM THE ARRAY TO THE LL
private static void display(Node head) {
if (head == null) return;
Node current = head;
while(current != null) {
System.out.print(current.data + " --> ");
current = current.next;
} System.out.println(current);
}
private static class Node{
private int data;
private Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public static void main(String args[]) {
Node head = new Node(5);
Node first = new Node(2);
Node second = new Node(3);
Node third = new Node(4);
Node fourth = new Node(1);
head.next = first;
first.next = second;
second.next = third;
third.next = fourth;
display(head);
System.out.println();
int arr[] = new int[count(head)];
passIntoArray(head, arr);
System.out.println();
}
}
【问题讨论】:
-
为什么不清除列表并将数组中的项目添加到空列表中?
-
实际上,当我将链表中的元素传递到数组中时,我试图打印出 LL,但它是空的。我想将数组元素传递到 LL
标签: java arrays algorithm linked-list