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 1printf("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++ 언어 링크드 리스트를 이용한 큐에서의 삽입과 삭제



+ Recent posts