我正在尝试创建一个程序,用户可以在其中将整数添加到链表中,然后它将计算最大数是多少,最小数是多少,数字的总和是多少,等等...我是遇到一些麻烦,我发现链接列表非常混乱,希望有人可以帮助我找出我做错了什么。
import java.util.*;
public class UnorderedLinkedListInt extends LinkedListIntClass {
int size=0;
LinkedList<Integer> list;
public boolean isEmptyList(){
if(size==0){
return true;
}else{return false;}
}
public void initializeList(){
list = new LinkedList<Integer>();
}
public void print(){
for(int x : list){
System.out.printf("%s ",x);
}
}
public int length(){
return size;
}
public int front(){
return list.getFirst();
}
public int back(){
return list.getLast();
}
public void insertFirst(int newItem){
list.addFirst(newItem);
}
public void insertLast(int newItem){
list.addLast(newItem);
}
public boolean search(int searchItem){
return list.contains(searchItem);
}
public void deleteNode(int deleteItem){
list.remove(deleteItem);
}
public int findSum(){
int sum =0;
for(int x:list){
sum=sum+x;
}
return sum;
}
public int findMin(){
int min =list.get(0);
for(int i=1;i<list.size();i++){
if(list.get(i)<min){
min=list.get(i);
}
}
return min;
}
public int findMax(){
int max=list.get(0);
for(int i=1;i<list.size();i++){
if(list.get(i)>max){
max=list.get(i);
}
}
return max;
}
}
这是我用来测试代码的客户端方法。
import java.util.*;
public class ClientUnorderedLinkedListInt {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
UnorderedLinkedListInt intList = new UnorderedLinkedListInt();
UnorderedLinkedListInt tempList;
int num;
System.out.println("Enter integers (999 to stop)");
num = input.nextInt();//valid??
while (num != 999) {
intList.insertLast((Integer) num);
num = input.nextInt();//valid??
}
System.out.print("\nTesting .insertLast and .print. The original list is: ");
intList.print();
System.out.println("\nTesting .length. The length of the list is: " + intList.length());
if (!intList.isEmptyList()) {
System.out.println("Testing .front. First element/list: " + intList.front());
System.out.println("Testing .back. Last element/list: " + intList.back());
}
System.out.println("Testing .sum. The sum of data in all nodes is: " + intList.findSum());
System.out.println("Testing .min. The smallest data in all nodes is: " + intList.findMin());
System.out.print("Testing .search. Enter the number to search for/list: ");
num = input.nextInt(); //valid??
if (intList.search(num))
System.out.println(num + " found in this list.");
else
System.out.println(num + " is not in this list.");
System.out.print("Testing .remove. Enter the number to be deleted from list: ");
num = input.nextInt();//valid??
intList.deleteNode(num);
System.out.print("Testing .toString. After deleting " + num + ", the list is: " + intList);
System.out.println("\nThe length of the list after delete is: " + intList.length());
}
}