Reputation: 33
Can someone help me understand whats happening in the following functions? Specifically the use of s1->top? And what is the movement of s1->top in the functions push &pop & display? Because if in function push, s1->top moves to the right whenever a number is pushed? then why in the display function, it says s1->top is first in the traversing, while in push s1->top is n the right, while in printing the values, we need to firstly be in the left and then traverse..why?
Stack createStack() {
Stack s1;
s1 = (Stack) malloc(sizeof(Stack_Head));
s1 - > count = 0;
s1 - > top = NULL;
return s1;
}
Nodeptr createNode(dataitem item) {
Nodeptr temp;
temp = (Nodeptr) malloc(sizeof(Node));
temp - > data = item;
temp - > next = NULL;
return temp;
}
void push(Stack s1, dataitem item) {
Nodeptr temp = createNode(item);
temp - > next = s1 - > top;
s1 - > top = temp;
s1 - > count++;
}
void display(Stack s1) {
Nodeptr ptr = s1 - > top;
while (ptr1 = NULL) {
printf("%d", ptr - > data);
ptr = ptr - > next;
}
printf("\n");
}
void pop(Stack s1) {
Nodeptr temp;
if (isEmpty(s1))
printf("List is Empty");
else {
temp = s1 - > top;
s1 - > top = temp - > next;
temp - > next = NULL;
free(temp);
s1 - > count;
}
int isEmpty(Stack s1) {
return s1 - > top == NULL;
}
Upvotes: 1
Views: 79
Reputation: 384
This stack structure is a LIFO, s1->top
is the top of the stack, i.e. the last pushed element. Each element points to the next element in the stack.
For example, here, the push
function creates a new element pointing to the data, makes this new element point to the last inserted element (which is its next element in the stack), and puts the new element at the top of the stack (s1->top = new_node
, where the new node here is called temp
).
Upvotes: 1
Reputation: 171
this is an implementation of a stack data structure.
Think of a lot of books that have been placed one on top of the other.
That would be a 'stack' of books.
Continuing with the stack of books analogy:
We start with an study table with nothing on it.
We can call this state as "There is no stack"
Then we write "Book Stack" on a blank paper and place it on the table.
We can call this state as "The stack is empty"
Lets 'Put' a Mathematics book on the stack.
Now the stack has one item, the Mathematics book, which is on top of the stack.
We 'Put' another book, Geography on the stack.
Now, we have two books on the stack and the Geogrphy book is the one on top.
Next, we 'Remove' the Geography book from the stack. Again the Mathematics book will be on the top.
Ok. The table is your computer. The paper with Book Stack written on it is a stack. Books are elements that can be placed on stack. 'Put' is called 'Push' 'Remove' is called 'Pop'
Upvotes: 1