어찌어찌 어설프게 구현해봤다...;;;;
괄호매칭 프로그램을 스택으로 구현하기 과제였는데..
자바로 링크드리스트 구현하는 예제가 별로 없어서 맨땅에 헤딩하듯이 구현했다.
프로그램 요구사항과 링크드리스트가 돌아가는 모양새를 대충 임시코드로 적어놓은 후에...
줄줄줄줄 문법대로 적어보니 어찌 에러없이 돌아가긴 한다;;;; 참 쉽죠잉~~~~ㅡ.ㅡ;;;;
평소에 워낙 코딩도 못 하고...제대로 한 줄 짜는 것 어려워서 덜덜덜 떨었는데...
조금씩 프로그래밍 실력이 늘어가는구나...생각이 든다.
확실히 #include 나 import java.io 부터 치고드는 것이 아니라..
뭘 만들어야 하는지 분석해서 그것을 노트에 그리거나 임시적으로 코드를 생성한 후..
차근차근 하나하나 만들어가는 것이 훨씬 더 쉽고 중요한 과정이라는 것을 절실하게 깨달았다.
이 코드가 비록 최적화 된 코드도 아니고 에러가 있을거라 생각하는데다가...(특히 null 할당부분)
링크를 중간에 추가하는 코드는 없지만 그래도 올려보자 아하하하하하
//////// 링크드리스트로 구현한 스택(MyStack.java)
public class MyStack
{
private String strData; // Data field on Node
private MyStack pNext; // Next Node Reference field
private MyStack pPrev; // previous Node Reference field
static private int countNode = 0; // number of Node and size counter for Stack
static private MyStack stackPointer = null; // Stack Pointer
static private MyStack tempPointer = null; // temp Pointer for deleteNode logic.
MyStack() // Constructor
{
this.pNext = null; // pNext initialize
this.pPrev = null; // pPrev initialize
}
public String getData() // interface (method) for get by Data field
{
return this.strData;
}
public void setData (String parenChar) // interface (method) for assign to Data field
{
this.strData = parenChar;
}
// Definition of Linked List
static void createNode(String inputParam) // create a new Node
{
if (countNode == 0) // make a Node
{
MyStack myList = new MyStack(); // instance of MyStack
myList.setData(inputParam); // set data to Data field
stackPointer = myList; // set stackPointer
countNode++; // increase countNode
}
else // add a Node
{
MyStack myList = new MyStack(); // instance of MyStack
// logic for add Node
stackPointer.pNext = myList;
myList.pNext = null;
myList.pPrev = stackPointer;
stackPointer = myList;
myList.setData(inputParam); // set data to Data field
countNode++; // increase countNode
}
} // end of createNode()
static void deleteNode() // delete Node
{
if (countNode == 0) // if none Node
{
System.out.println("NG.");
System.exit(1);
}
else // can delete node
{
if (countNode >= 2) // have two nodes
{
// logic for delete node
tempPointer = stackPointer.pPrev;
stackPointer = null;
stackPointer = tempPointer;
stackPointer.pNext = null;
tempPointer = null;
countNode--; // decrease countNode
}
else // have one node
{
stackPointer = null;
countNode--;
}
} // end of if
} //end of deleteNode
// Linked List Definition End
//start Definition of Stack
public void pop() // pop method
{
if ( empty() ) // if stack is empty, means none node
{
System.out.println("==>Stack overflow"); // Stack overflow
System.exit(1);
}
deleteNode(); // function call to deleteNode
}
public void push(String inputStr) // pust method
{
if ( full() ) // if stack is full, means have more than 10 nodes
{
System.out.println("==>Stack underflow"); // Stack underflow
System.exit(1);
}
createNode(inputStr); // function call to CreateNode with inputString
}
public boolean empty() // check stack empty
{
boolean testEmpty = true;
if ( countNode == 0 )
testEmpty = true;
else
testEmpty = false;
return testEmpty;
} // end of empty
public boolean full() // check stack full
{
boolean testFull = true;
if ( countNode >= 10 )
testFull = true;
else
testFull = false;
return testFull;
} // end of IsFull()
} // end of MyStack()
//////////// 여기서부터는 괄호매칭 로직 (Balanced.java)
public class Balanced {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java Balanced PARENTHESES");
System.exit(1);
}
String in = args[0];
System.out.println("Input string: " + in);
Balanced b = new Balanced();
b.parse(in);
}
/**
* @param input a parenthesis string
*/
public void parse(String input) {
int check = 0;
char ch;
MyStack stack = new MyStack();
for (int i = 0; i < input.length(); i++) {
ch = input.charAt(i);
if (ch == '(') {
if (!stack.full()) {
stack.push("(");
check++;
} else {
System.out.println("==>Stack overflow");
error();
}
} else if (ch == ')') {
if (!stack.empty()) {
stack.pop();
check--;
} else {
System.out.println("==>Stack underflow");
error();
}
} else {
System.out.println("Invalid character parsed.");
error();
}
}
if (stack.empty()) {
System.out.println("OK.");
} else {
error();
}
}
void error() {
System.out.println("NG.");
System.exit(1);
}
}
댓글
댓글 쓰기