作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试编写代码让用户输入正整数并将它们发送到链表。用户输入应在输入负数后结束。此外,我在编写 isSorted boolean 方法时遇到问题,如果链表按递增顺序排序,该方法将返回 true,否则返回 false。
这是我目前唯一的代码
import java.util.*;
public class List {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type positive integers one by one separated by a space.");
System.out.println("When you are done, please type a negative integer.");
int num = input.nextInt();
}
public boolean isSorted(){
if(){
return true;
}
else{
return false;
}
}
}
最佳答案
public void input() {
System.out.println("Please type positive integers one by one separated by a space.");
System.out.println("When you are done, please type a negative integer.");
LinkedList<Integer> ll = new LinkedList<>();
//System.in.available()
Scanner input = new Scanner(System.in);
int num;
while ( input.hasNextInt() ) {
int i = input.nextInt();
if (i >= 0) {
ll.add(i);
}
}
System.out.println(ll+" <-- ll"); //TODO remove debugging code
System.out.println(isSortedAccending(ll)+" <-- isSortedAccending(ll)");//TODO
}
这通过返回 false
来实现发现有问题的那一刻。
public static boolean isSortedAccending(List<Integer> list){
if (list.size() < 2) {
return true;
}
Integer previous = list.get(0);
for (Integer next : list) {
if (previous > next) {
return false;
}
}
return true;
}
输出:
Please type positive integers one by one separated by a space.
When you are done, please type a negative integer.
1
2
3
-1
[1, 2, 3] <-- ll
true <-- isSortedAccending(ll)
isSortedDecending()
除了使用 <
外,看起来完全一样.
关于java - 如何将用户输入的整数发送到 Java 中的链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29241109/
我是一名优秀的程序员,十分优秀!