使用排序的String值填充空堆栈

时间:2017-09-30 01:29:29

标签: java stack structure

我有一个字符串值数组(未排序)。我的目标是对这些值进行排序,然后将它们推送到空堆栈中。我无法解决的问题是,当我将具有最低字符的字符串push()到我的堆栈中时,我找不到删除该字符串的方法,以便下次我的循环迭代时,该字符串不会再次与下一个最低点。我知道我可能会采用错误的方法,但我认为这是练习我的数据结构类的好方法。这是我的代码:

import java.util.*;

public class StackClass {
    public static void main(String[] args) {
        Stack<String> name = new Stack<String>();
        String arr[] = {"Camila",  "Zury", "Diego",
        "Gabriela","Brian","Fabian", "Harry","Martin", "Luis", "Anderson",};    
        String minChar;
        minChar= arr[0];
        for (int i = 1; i < arr.length; i++) {  
            if(arr[i].charAt(0) < minChar.charAt(0)) {// to compare the lowest char    
                minChar = arr[i]; //lowest char = minChar   
            }
        }
        name.push(minChar); //minChar is pushed into the stack.
        System.out.println(name);
    }
}

2 个答案:

答案 0 :(得分:0)

如果要使用字符串(ArrayList<String>)的数组列表,则只需使用remove(item)函数,因为ArrayLists支持动态调整大小。

不幸的是,数组的长度是固定的,因此您的选项的一个选项是删除arr[i]的对象引用。例如

if(arr[i].charAt(0) < minChar.charAt(0)) {// to compare the lowest char    
            minChar = arr[i]; //lowest char = minChar 
            arr[i] = null; //this will remove the object reference but not resize the array  
        }

答案 1 :(得分:0)

public static void main(String[] args) {

    String names[] = { "Peter", "Patricia", "Hunter", "Sarah",
            "Gabe", "Gina", "Rob", "John", "Zoey", "Tammy", "Robert",
            "Sean", "Paschal", "Kathy", "Nill", "Val" };
    Stack<String> stack = new Stack<>();

    Arrays.sort(names); 

    for (String name: names) {
        stack.push(name);
    }

    //test
    for (String name: stack) {
        System.out.println(name);
    }
}