2016-09-11 6 views
0

스택이 꽉 찼을 때 (예 : 5 개의 값을 보유 할 수있는 경우) DropOut 메소드를 수행하는 다른 값을 스택에 푸시하려고하는 프로그램을 만들려고합니다. 예 세트는 어디 있습니까? 위치 0에서 1 등 위치에 스택. 위치를 3 == 4로 이동하는 모든 방법. 여기에서 스택의 맨 위 값을 삭제합니다 (이 예제에서는 위치 4의 값입니다 (5 번째 값)) 여기에서 다음 스택의 맨 위에 내 다음 값을 추가 할 수 ....하지만 내 코드 의도 한대로 작동하지 않습니다. 나는 초보자이며 사용 가능한 모든 입력에 감사드립니다. 시간 내 주셔서 감사합니다.드롭 아웃 스택이 작동하지 않습니다.

package jsjf; 

import jsjf.exceptions.*; 
import java.util.Arrays; 
import java.util.*; 


public class ArrayStack1<T> implements StackADT<T> 
{ 
    private final static int DEFAULT_CAPACITY = 5; 

    private int top; 
    private T[] stack; 
    private int next; 

public ArrayStack1() 
    { 
     this(DEFAULT_CAPACITY); 
} 


public ArrayStack1(int initialCapacity) 
{ 
    top = -1; 
    stack = (T[])(new Object[initialCapacity]); 


} 


    public void push(T element) 
{ 

    if (top+1==DEFAULT_CAPACITY){ 
    DropOut(); 
    //top=top-1; 
    pop(); 
    stack[top]=element; 
    } 
    top++; 
    stack[top] = element; 

} 



    public void DropOut(){ 

    for (int x=0; x<stack.length-1; x++){ 
    // if(x==stack.length){ 
    // stack[x]=null; 
    // } 
     stack[x]=stack[x+1]; 
    } 


    } 

    public T pop() throws EmptyCollectionException 
{ 
    if (isEmpty()) 
     throw new EmptyCollectionException("stack"); 


    T result = stack[top]; 
    stack[top] = null; 

    return result; 
} 


    public T peek() throws EmptyCollectionException 
{ 
    if (isEmpty()) 
     throw new EmptyCollectionException("stack"); 

    return stack[top]; 
} 


    public boolean isEmpty() 
{ 
    return (top < 0); 
} 


public int size(){ 
return (top+1); 
} 



    public String toString() 
{ 
    String result = ""; 

    for (int scan=0; scan <= top; scan++) 
    result = result + stack[scan].toString() + "\n"; 

    return result; 
} 

public static void main(String[] args) { 

    ArrayStack1<Integer> t1=new ArrayStack1<Integer>(5); 
    t1.push(5); 
    t1.push(3); 
    t1.push(6); 
    t1.push(5); 
    t1.push(3);// 
    t1.push(4); 

} 
} 

답변

0

push 최대 용량에 도달하면 요소를 두 번 쌓습니다. else으로 문제를 해결해야합니다.

public void push(T element) 
{ 

    if (top+1==DEFAULT_CAPACITY){ 
     DropOut(); 
     //top=top-1; 
     pop(); 
     stack[top]=element; 
    } else { 
     top++; 
     stack[top] = element; 
    } 
} 
+0

한숨 ... 나는 그것을 어떻게 보았습니까! haha 그 긴 날이었다! –

관련 문제