답이 될런지..


[ 다음 글들 ] [ 이어서 글올리기(답하기) ] [ 자바 묻고 답하기 ]

글쓴이 :위성혁 2000년 5월 05일 23:13:37

In Reply to: int 형 Stack좀 만들어 주세요.. posted by 도움주실분.. on 2000년 5월 05일 21:00:14:

public class ExIntStack
{
private Node first;
class Node
{
private int data;
private Node next;
public Node(int input)
{
data = input;
next = null;
}
public void setNext(Node nextNode)
{
next = nextNode;
}
public int getData()
{
return data;
}
public Node getNextNode()
{
return next;
}

}


public void push(int data)
{
if(!isEmpty()){
Node newNode = new Node(data) ;
newNode.setNext(first);
first = newNode;
}
else{
first = new Node(data);
}
}

public Node pop()
{
if(isEmpty())
return null;
else{
Node temp = new Node(first.getData());
first = first.getNextNode();
return temp;
}
}

public boolean isEmpty()
{
if(first==null)
return true;
else
return false;
}

public void printStack(Node node)
{
if(node==null)
return;
printStack(node.getNextNode());
System.err.println(" "+node.getData());
}
public Node getTop()
{
return first;
}

public static void main(String [] args)
{
ExIntStack ex = new ExIntStack();
ex.push(5);
ex.push(6);
ex.printStack(ex.getTop());
Node data = ex.pop();
if(data!=null)
System.err.println(" " + data.getData());
data = ex.pop();
if(data!=null)
System.err.println(" " + data.getData());
data = ex.pop();
if(data!=null)
System.err.println(" " + data.getData());



}


}


// 지져분한 program이 된것 같습니다 제 나름대로 급하게 작성한 program이라서.. 자신은 없지만 되움이 되면 좋겠습니다. java에서는 pointer가 없고 모든 Object에 대해서 call-by-reference로 되기 때문에 pop할때 새로운 node 를 만들어서 return 해 주어야 될 듯 합니다. 또한 data만 return 할려면 좋은데 error를 check 할 수 가 없죠 그래서 Node 를 return 하도록 하였습니다. return 된 node가 null 이면 더이상 스택에 node가 없으니까요 만약에 data만 return 하고 싶으시다면 exception을 만들어셔 error를 check 하도록 만드시면 될 듯 합니다. (잘 모르시겠다면 메일 주세요



다음 글들:



이어서 글올리기(답하기)

이름:
E-Mail:
제목:
내용:
HTML 태그 포함 여부: HTML 문서일 경우 체크
관련 URL(선택):
URL 제목(선택):
관련 이미지 URL:


[ 다음 글들 ] [ 이어서 글올리기(답하기) ] [ 자바 묻고 답하기 ]