C/C++ 언어 링크드 리스트를 이용한 큐에서의 삽입과 삭제
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 115 116 117 118 119 120 121 | #include <stdio.h> #include <stdlib.h> struct queueNode { /* 자기 참조 구조체 */ char data; struct queueNode *nextPtr; }; typedef struct queueNode QUEUENODE; typedef QUEUENODE *QUEUENODEPTR; void printQueue(QUEUENODEPTR); int isEmpty(QUEUENODEPTR); char dequeue(QUEUENODEPTR *, QUEUENODEPTR *); void enqueue(QUEUENODEPTR *, QUEUENODEPTR *, char); void instructions(void); int main(void) { QUEUENODEPTR headPtr = NULL, tailPtr = NULL; int choice; char item; while(1) { instructions(); printf("? "); fflush(stdin); scanf("%d", &choice); if (3 == choice) { break; } switch(choice) { case 1: printf("Enter a character: "); fflush(stdin); scanf("\n%c", &item); enqueue(&headPtr, &tailPtr, item); printQueue(headPtr); break; case 2: if (!isEmpty(headPtr)) { item = dequeue(&headPtr, &tailPtr); printf("%c has been dequeued. \n",item); } printQueue(headPtr); break; default: printf("Invalid choice. \n\n"); instructions(); break; } } printf("End of run. \n"); return 0; } void instructions(void) { printf("Enter your choice:\n" " 1 to add an item to the queue\n" " 2 to remove an item from the queue\n" " 3 to end\n"); } void enqueue(QUEUENODEPTR *headPtr, QUEUENODEPTR *tailPtr, char value) { QUEUENODEPTR newPtr; newPtr = (QUEUENODE*)malloc(sizeof(QUEUENODE)); if (newPtr != NULL) { newPtr ->data = value; newPtr ->nextPtr = NULL; if (isEmpty(*headPtr)) *headPtr = newPtr; else (*tailPtr)->nextPtr = newPtr; *tailPtr = newPtr; } else { printf("%c not inserted.", value); printf(" No memory available.\n"); } } char dequeue(QUEUENODEPTR *headPtr, QUEUENODEPTR *tailPtr) { char value; QUEUENODEPTR tempPtr; value = (*headPtr)->data; tempPtr = *headPtr; *headPtr = (*headPtr) -> nextPtr; if (*headPtr == NULL) *tailPtr = NULL; free(tempPtr); return value; } void printQueue(QUEUENODEPTR currentPtr) { /* Print the queue */ if (currentPtr == NULL) printf("The queue is empty. \n\n"); else { printf("The queue is:\n"); while (currentPtr != NULL) { printf("%c --> ", currentPtr->data); currentPtr = currentPtr->nextPtr; } printf("NULL\n\n"); } } int isEmpty(QUEUENODEPTR headPtr) { /* Is the stack empty? */ return headPtr == NULL; } | cs |
C/C++ 언어 링크드 리스트를 이용한 큐에서의 삽입과 삭제
'C,C++ > 예제' 카테고리의 다른 글
| C/C++ 언어 키보드에서 입력한 문자의 ASCII 코드 값의 2진수 출력 (0) | 2016.01.29 |
|---|---|
| C/C++ 언어 하노이 탑/타워 예제 (0) | 2016.01.29 |
| C/C++ 언어 이진 트리를 생성하고 전위, 중위, 후위 순회 연산 결과를 구하는 예제 (0) | 2016.01.28 |
| C/C++ 언어 fopen, fscanf, fprintf 문자 입력 받아서 파일에 저장하고 화면에도 출력 (0) | 2016.01.28 |
| C/C++ 언어 for문 사용 한글 "가"에서 "힝"까지 출력하기 (0) | 2016.01.28 |