stack_linked_list.c
stacks Implementation
69 lines1165 bytesC
1// Stack using Linked List
2#include <stdio.h>
3#include <stdlib.h>
4
5struct Node {
6 int data;
7 struct Node* next;
8};
9
10struct Node* top = NULL;
11
12void push(int data) {
13 struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
14 newNode->data = data;
15 newNode->next = top;
16 top = newNode;
17 printf("Pushed %d\n", data);
18}
19
20int pop() {
21 if (top == NULL) {
22 printf("Stack Underflow!\n");
23 return -1;
24 }
25 struct Node* temp = top;
26 int data = temp->data;
27 top = top->next;
28 free(temp);
29 return data;
30}
31
32int peek() {
33 if (top == NULL) {
34 printf("Stack is empty!\n");
35 return -1;
36 }
37 return top->data;
38}
39
40void display() {
41 if (top == NULL) {
42 printf("Stack is empty!\n");
43 return;
44 }
45 struct Node* temp = top;
46 printf("Stack: ");
47 while (temp != NULL) {
48 printf("%d -> ", temp->data);
49 temp = temp->next;
50 }
51 printf("NULL\n");
52}
53
54int main() {
55 push(10);
56 push(20);
57 push(30);
58 push(40);
59
60 display();
61
62 printf("Top element: %d\n", peek());
63 printf("Popped: %d\n", pop());
64
65 display();
66
67 return 0;
68}
69