Skip to content

Commit 05e6d2a

Browse files
committed
Stack using Linked List added
1 parent 0ecc7da commit 05e6d2a

File tree

2 files changed

+81
-1
lines changed

2 files changed

+81
-1
lines changed

Data Structure/Stack/README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,12 @@ To use a stack efficiently, we need to check the status of stack as well. For th
2525
- **isEmpty()** − check if stack is empty.
2626

2727

28-
####Complexity Analysis
28+
#### Complexity Analysis
2929
- Insertion - O(1)
3030
- Deletion - O(1)
3131
- Access - O(n)
3232
- Search - O(n)
33+
3334
### More on this topic
3435
- https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
3536
- https://www.tutorialspoint.com/data_structures_algorithms/stack_algorithm.htm
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
#include<stdio.h>
2+
#include<stdlib.h>
3+
4+
typedef struct
5+
{
6+
int val;
7+
struct node* next;
8+
}node;
9+
10+
node* top = NULL;
11+
12+
void push(int value)
13+
{
14+
node* tmp=(node*) malloc(sizeof(node)); //memory allocating for a node
15+
16+
tmp->val = value;
17+
tmp->next = top; //add this new value at the end of the stack
18+
19+
top = tmp; //now top of the stack is the new node
20+
}
21+
22+
void pop()
23+
{
24+
node* tmp;
25+
26+
if(top==NULL)
27+
printf("Stack is empty\n");
28+
else
29+
{
30+
printf("popped element %d\n",top->val);
31+
tmp=top;
32+
33+
top=top->next; //top is replaced to the next node
34+
35+
free(tmp); //top node is deleted from the memory
36+
}
37+
}
38+
39+
int peek()
40+
{
41+
if(top != NULL)
42+
return (int)top->val;
43+
44+
return top;
45+
}
46+
47+
int main()
48+
{
49+
int action,value;
50+
int exit = 0;
51+
52+
while(!exit)
53+
{
54+
printf("Enter Action: \n 1.Insert \n 2.Get Top Value \n 3.Exit\n");
55+
scanf("%d",&action);
56+
57+
switch(action)
58+
{
59+
case 1:
60+
printf("Enter Value: ");
61+
scanf("%d",&value);
62+
63+
push(value);
64+
65+
printf("Element at top of the stack: %d\n", peek());
66+
67+
break;
68+
case 2:
69+
pop();
70+
71+
break;
72+
case 3:
73+
exit = 1;
74+
break;
75+
}
76+
}
77+
78+
return 0;
79+
}

0 commit comments

Comments
 (0)