問題陳述:
創建一個程式,初始化字符陣列中的單詞(這將成為您的堆疊)并顯示洗掉堆疊中最后一個字母的單詞。
例子
輸入:
LONELY
輸出:
LONELY
LONEL
LONE
LON
LO
L
所以這是我的代碼,我只能在陣列上列印字符。
但是我還沒有想出一個解決方案來繼續洗掉最后一個字母,就像輸出顯示的那樣。
并且可能需要它是合乎邏輯的。
public static void main(String[] args) {
char word[] = {'S', 'T', 'U', 'C', 'K'};
int len = word.length;
for (int x = 0; x < len; x ) {
System.out.print(word[x]);
}
}
uj5u.com熱心網友回復:
您可以使用嵌套for
回圈。
內回圈的變數指向一個特定的字符。而外回圈中定義的變數表示當前行需要跳過的字符數。
陳述句System.out.println()
在每個內部回圈之后執行,并將輸出推進到下一行。
public static void main(String[] args) {
char word[] = {'L', 'O', 'N', 'E', 'L', 'Y'};
int len = word.length;
for (int i = 0; i < len; i ) {
for (int j = 0; j < len - i; j ) {
System.out.print(word[j]); // printing a row
}
System.out.println(); // advancing output to the next line
}
}
但是,如果您的挑戰意味著您需要創建一個將由字符陣列支持的堆疊資料結構的實作,那將是一項更復雜的任務。
下面的代碼旨在提供有關如何使用它的一般想法。
在堆疊的實作中必須存在三個重要的方法:
push()
- 添加新元素(在方法主體中我提供了說明,但省略了此實作,以便您有機會獲得實踐經驗);pop()
- 從堆疊頂移除元素并回傳;peek()
- 從堆疊頂回傳元素而不移除它。
此外,我添加了可用于檢查堆疊是否為空并列印其內容的實作isEmpty()
和方法,正如它們的名字所暗示的那樣。print()
class CharacterStack {
private char[] letters;
private int pos = -1;
public CharacterStack(int size) { // size is passed as an argument
this.letters = new char[size]; // creating an empty array of characters
}
public CharacterStack(char[] letters) { // array of characters is passed as an argument
this.letters = letters;
this.pos = letters.length - 1; // position at the top of the stack - the greatest valid index of the array
}
public void push(char letter) {
/* to do:
1. check the length of the array
2. if current position doesn't fit in to it create a new array with greater length
3. copy the contents of the previous array into a new array
4. re-assign the variable `letters` to be a newly created array
*/
}
public char pop() { // removing the element from the top of the stack and returning it
// return letters[pos--]; a concise equivalent of the lines below
char result = letters[pos];
pos--;
return result;
}
public char peek() { // returning the element from the top of the stack without removing it
return letters[pos];
}
public boolean isEmpty() {
return pos == -1;
}
public void print() {
for (int i = 0; i <= pos; i ) {
System.out.print(letters[i]);
}
}
}
main()
- 演示
public static void main(String[] args) {
char[] word = {'L', 'O', 'N', 'E', 'L', 'Y'};
int len = word.length;
CharacterStack stack = new CharacterStack(word);
while (!stack.isEmpty()) {
stack.print(); // printing the contents of the stack
System.out.println(); // advancing output to the next row
stack.pop(); // removing the element from the top of the stack
}
}
輸出
LONELY
LONEL
LONE
LON
LO
L
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/469958.html