-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedlist.c
86 lines (69 loc) Β· 1.41 KB
/
linkedlist.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
#include <stdlib.h>
#include <stdio.h>
struct Node{
int data;
struct Node *next;
}*top=NULL;
struct Node *newNode(int data){
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->next = NULL;
temp->data = data;
return temp;
}
void push(int x){
struct Node *nNode;
nNode = newNode(x);
nNode->next = top;
top = nNode;
}
void display(){
struct Node *temp = top;
if(top == NULL){
printf("List is empty!");
}else{
while(temp!=NULL){
printf("\nElement : %d",temp->data);
temp = temp->next;
}
}
}
int pop(){
int x =-1;
struct Node *temp = top;
if(top == NULL){
return x;
}else {
x = top->data;
top = top->next;
free(temp);
return x;
}
}
// used to return top element
int peek(){
if(top == NULL){
return -1;
}else {
return top->data;
}
}
int main()
{
push(10);
push(20);
display();
int x = pop();
if (x != -1) { // Corrected the condition check
printf("\nValue is deleted from stack: %d\n", x);
} else {
printf("\nStack is empty\n");
}
display(); // Display the stack after popping
int topElement = peek();
if(topElement!=-1){
printf("\nTop element : %d" , topElement);
}else{
printf("\nStack is empty !");
}
return 0;
}