C/C++ 언어 링크드 리스트를 이용한 스택에서의 push와 pop 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | #include <stdio.h> #include <stdlib.h> struct stackNode { /* 자기 참조 구조체 */ int data; struct stackNode *nextPtr; }; typedef struct stackNode STACKNODE; typedef STACKNODE * STACKNODEPTR; void push(STACKNODEPTR *, int); int pop(STACKNODEPTR *); int isEmpty(STACKNODEPTR); void printStack(STACKNODEPTR); void instructions(void); int main(void) { STACKNODEPTR stackPtr = NULL; /* points to the stack top */ int choice, value; while (1) { instructions(); printf("? "); fflush(stdin); scanf("%d", &choice); if (3 == choice) { break; } switch (choice) { case 1: /* push value onto stack */ printf("Enter an integer: "); fflush(stdin); scanf("%d", &value); push(&stackPtr, value); printStack(stackPtr); break; case 2: /* pop value off stack */ if (!isEmpty(stackPtr)) printf("The popped value is %d.\n",pop(&stackPtr)); printStack(stackPtr); break; default: printf("Invalid choice. \n\n"); break; } } printf("End of run. \n"); return 0; } void instructions(void) { /* Print the instructions */ printf("Enter choice: \n" "1 to push a value on the stack\n" "2 to pop a value off the stack\n" "3 to end program\n"); } void push(STACKNODEPTR *topPtr, int info) { /* 스택의 탑에 원소 삽입 */ STACKNODEPTR newPtr; newPtr = (STACKNODE*)malloc(sizeof(STACKNODE)); if (newPtr != NULL){ newPtr->data = info; newPtr->nextPtr = *topPtr; *topPtr = newPtr; } else printf("%d not inserted. No memory available. \n", info); } int pop(STACKNODEPTR *topPtr) { /* 스택 탑으로부터 노드 삭제 */ STACKNODEPTR tempPtr; int popValue; tempPtr = *topPtr; popValue = (*topPtr)->data; *topPtr = (*topPtr)->nextPtr; free(tempPtr); return popValue; } void printStack(STACKNODEPTR currentPtr) { /* Print the stack */ if (currentPtr == NULL) printf("The stack is empty. \n\n"); else { printf("The stack is:\n"); while (currentPtr != NULL) { printf("%d --> ", currentPtr->data); currentPtr = currentPtr->nextPtr; } printf("NULL\n\n"); } } int isEmpty(STACKNODEPTR topPtr) { /* Is the stack empty? */ return topPtr == NULL; } | cs |
C/C++ 언어 링크드 리스트를 이용한 스택에서의 push와 pop 예제
'C,C++ > 예제' 카테고리의 다른 글
C/C++ 언어 getchar() 함수 버퍼 문제 (0) | 2016.02.02 |
---|---|
C/C++ 언어 키보드 입력 버퍼 확인 _kbhit() (0) | 2016.02.02 |
C/C++ 언어 키보드에서 입력한 문자의 ASCII 코드 값의 2진수 출력 (0) | 2016.01.29 |
C/C++ 언어 하노이 탑/타워 예제 (0) | 2016.01.29 |
C/C++ 언어 링크드 리스트를 이용한 큐에서의 삽입과 삭제 (0) | 2016.01.29 |