Week 7-1 : Stack, Queue by Linked List
Tutoring/18-1 DS2018. 5. 19. 01:21
<180517>
- 연결리스트로 구현한 스택
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 | #include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *link; } Node; typedef struct stack { Node *top; } Stack; void init(Stack *ps) { ps->top = NULL; } int isEmpty(Stack *ps) { return ps->top == NULL; } void push(Stack *ps, int data) { Node *newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->link = NULL; if(!isEmpty(ps)) newNode->link = ps->top; ps->top = newNode; } int peek(Stack *ps) { return ps->top->data; } int pop(Stack *ps) { Node *delNode = ps->top; int ret = delNode->data; ps->top = ps->top->link; free(delNode); return ret; } int main() { Stack s; init(&s); isEmpty(&s) ? puts("Empty") : puts("No"); push(&s, 10); push(&s, 20); if(!isEmpty(&s)) printf("%d\n", peek(&s)); if(!isEmpty(&s)) printf("%d\n", pop(&s)); if(!isEmpty(&s)) printf("%d\n", peek(&s)); return 0; } | cs |
>> 실행결과
Empty
20
20
10
- 연결리스트로 구현한 큐
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 | #include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *link; } Node; typedef struct queue { Node *f, *r; } Queue; void init(Queue *pq) { pq->f = pq->r = NULL; } int isEmpty(Queue *pq) { return pq->f == NULL; } void enqueue(Queue *pq, int data) { Node *newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->link = NULL; if(isEmpty(pq)) pq->f = newNode; else pq->r->link = newNode; pq->r = newNode; } int peek(Queue *pq) { return pq->f->data; } int dequeue(Queue *pq) { Node *delNode = pq->f; int ret = delNode->data; pq->f = pq->f->link; free(delNode); return ret; } int main() { Queue q; init(&q); isEmpty(&q) ? puts("Empty") : puts("No"); enqueue(&q, 10); enqueue(&q, 20); if(!isEmpty(&q)) printf("%d\n", peek(&q)); if(!isEmpty(&q)) printf("%d\n", dequeue(&q)); if(!isEmpty(&q)) printf("%d\n", peek(&q)); return 0; } | cs |
>> 실행결과
Empty
10
10
20
'Tutoring > 18-1 DS' 카테고리의 다른 글
Week 8-1 : Binary Tree 2 (0) | 2018.06.05 |
---|---|
Week 7-2 : Tree, Binary Tree (0) | 2018.05.27 |
Week 6 : Maze(with stack) / Circular Queue (0) | 2018.05.16 |
Week 5-2 : infix to postfix, exp(postfix) (0) | 2018.05.08 |
Week 5-1 : Circular Doubly Linked List / Stack ADT (0) | 2018.05.08 |