这是我的代码
import java.util.Scanner;
import java.io.File;
import java.util.*;
import java.io.*;
class BubbleSort{
static class Node {
int val;
Node next;
Node (int x) {
val = x;
next = null;
}
}
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File(args[0]));
Node insertion = new Node(scanner.nextInt());
Node intNodes = insertion;
while(scanner.hasnextInt()){
Node nextNode = new Node(scanner.nextInt());
insertion.next = nextNode;
insertion = nextNode;
}
intNodes = bubbleSortList(intNodes);
printList(intNodes);
}
public static Node bubbleSortList(Node head) {
int swapped,i;
Node x;
Node y = null;
if (head == null)
return null;
do
{
swapped = 0;
x = head;
while (x.next != y)
{
if (x.val < x.next.val)
{
int t = x.val;
x.val = x.next.val;
x.next.val = t;
swapped = 1;
}
x = x.next;
}
y = x;
}
while (swapped != 0);
return head;
}
public static void printList(Node n) {
while (n != null) {
System.out.print(n.val + " ");
n = n.next;
}
}
}
它有效,我的问题是列表的末尾有一个空格,并且有一种摆脱它的方法。 它会输出:10space9space8space7space6space5space4space3space2space1space。 我想要的是10space9space8space7space6space5space4space3space2space1 ...我以“空格”为参考