Skip to content

Commit a967b45

Browse files
Spart-v6abranhe
authored andcommitted
stack using linked list
1 parent 0f9942e commit a967b45

File tree

1 file changed

+107
-0
lines changed

1 file changed

+107
-0
lines changed
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
#include<iostream>
2+
#include<cstdio>
3+
4+
using namespace std;
5+
6+
//- Global Variable (came from main)!
7+
struct Node *top = NULL;
8+
9+
struct Node{
10+
int data;
11+
struct Node *next;
12+
};
13+
14+
void linkedlistTraversal(struct Node * ptr){
15+
while(ptr!=NULL){
16+
printf("Element: %d\n", ptr->data);
17+
ptr = ptr->next;
18+
}
19+
}
20+
21+
int isEmpty(struct Node* top){
22+
if(top == NULL){
23+
return 1;
24+
}
25+
return 0;
26+
}
27+
28+
int isFull(struct Node* top){
29+
struct Node * n = (struct Node *) malloc(sizeof(struct Node));
30+
if(n == NULL){
31+
return 1;
32+
}
33+
return 0;
34+
}
35+
36+
struct Node* push(struct Node* top, int data){
37+
if(isFull(top)){
38+
printf("Stack Overflow!\n");
39+
}
40+
else{
41+
struct Node * n = (struct Node*) malloc(sizeof(struct Node));
42+
n->data = data;
43+
n->next = top;
44+
top = n;
45+
return top;
46+
}
47+
}
48+
49+
int pop(struct Node * tp){
50+
if(isEmpty(tp)){
51+
printf("Stack Underflow!");
52+
}
53+
else{
54+
struct Node * n = tp;
55+
top = (tp)->next;
56+
int x = n->data;
57+
free(n);
58+
return x;
59+
}
60+
}
61+
62+
int peek(int pos){
63+
struct Node * ptr = top;
64+
for (int i = 0; (i < pos-1 && ptr!=NULL); i++)
65+
{
66+
ptr = ptr->next;
67+
}
68+
if(ptr!=NULL){
69+
return ptr->data;
70+
}
71+
else{
72+
return -1; // assuming there's no -ve element in stack
73+
}
74+
}
75+
76+
int stackTop(struct Node * top){
77+
return top->data;
78+
}
79+
80+
int stackBottom(struct Node * top){
81+
struct Node * p = top;
82+
while(p->next!=NULL){
83+
p = p->next;
84+
}
85+
return p->data;
86+
}
87+
88+
int main()
89+
{
90+
top = push(top, 69);
91+
top = push(top, 10);
92+
top = push(top, 8);
93+
top = push(top, 7);
94+
linkedlistTraversal(top);
95+
96+
for (int i = 1; i <= 4; i++)
97+
{
98+
printf("The element at position %d is %d\n",i,peek(i));
99+
}
100+
101+
// printf("The top most element in stack is %d\n",stackTop(top));
102+
printf("The bottom most element in stack is %d\n",stackBottom(top));
103+
104+
105+
106+
return 0;
107+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy