c - Movement & starting point of s1->top in the following functions, push, display & pop -
can me understand whats happening in following functions? use of s1->top? , movement of s1->top in functions push &pop & display? because if in function push, s1->top moves right whenever number pushed? why in display function, says s1->top first in traversing, while in push s1->top n right, while in printing values, need firstly in left , traverse..why?
typedef struct node* nodeptr; typedef char dataitem; typedef struct node{ dataitem data; nodeptr next; }node; typedef struct{ int count; nodeptr top; }stack_head; typedef stack_head* stack; 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 (ptr != null) { printf("%d", ptr - > data); ptr = ptr - > next; } printf("\n"); } void pop(stack s1) { nodeptr temp; if (isempty(s1)) printf("list empty"); else { temp = s1 - > top; s1 - > top = temp - > next; temp - > next = null; free(temp); s1 - > count; } int isempty(stack s1) { return s1 - > top == null; }
first off, let's fix bug - in function display()
, assume line :
while (ptr1 = null) {
should :
while (ptr != null) {
in question, refer "left" , "right", variable "top" implies, it's easier visualising vertical stack.
for example, imagine stack of dinner plates. new plates "push"ed onto top, , on demand "popped" top.
so can see, sort of stack called last-in-first-out (or lifo) stack, , code implementing.
the s1->top
variable pointer top of stack - ie. last node added, first removed. each node has pointer next
node "under" it. null used indicate "no more nodes", both s1->top
, , node->next
pointers.
so in push()
, 2 things must happen consistency :
- the new arrival's
->next
pointer must set current "top" of stack (so existing top "under" new arrival), , - the new arrival must set new "top".
note order of operations here important - if (2) performed before (1), end new arrival's "->next" pointer pointing !
pop()
performs operations in reverse, , display()
runs down elements in stack (notice display()
not alter value of s1->top
).
Comments
Post a Comment