CS DataStructure-Lecture 2-Linked Stack
CS DataStructure-Lecture 2-Linked Stack
pn
New
node
}
CreateStack
&s The execution time does not
ps depend on anything, therefore
the complexity is: Θ(1)
s.top
s
© Waleed A. Yousef 2008 7
/* Pre: The stack exists and is initialized.
Post: The argument item has been stored at the top of the stack
*/
Push entry
e
e pn
&s Old top Old bottom
ps node node
© Waleed A. Yousef 2008 s 8
Always take care of special cases
/* Pre: The stack exists and is initialized
Post: The argument item has been stored at the top of the stack */
Push entry
e
e pn
&s
ps
© Waleed A. Yousef 2008 s 9
/*Pre: The stack exists and it is not empty.
Post: The item at the top of the stack has been removed and returned
in *pe */
&e
pe pn
&s 2nd top Old bottom
ps node node
© Waleed A. Yousef 2008 s 10
Always take care of special cases
/*Pre: The stack exists and it is not empty.
Post: The item at the top of the stack has been
removed and returned in *pe */
User Call:
void Pop(StackEntry *pe, Stack *ps){ Stack s;
StackNode *pn; StackEntry e;
*pe=ps->top->entry;
pn=ps->top; Pop(&e, &s);
ps->top=ps->top->next;
free(pn); 1 st element
} e
&e
pe pn
&s
ps
© Waleed A. Yousef 2008 s 11
/* Pre: The stack exists
Post: returns the status, 1 or 0*/
int StackEmpty(Stack *ps){ For any function that does not change
return ps->top==NULL; the stack there is no problem in passing
} the stack itself s rather than a pointer
to it ps. This will not copy the elements
int StackFull(Stack *ps){ as opposed to the array-based
return 0;
implementation. However, of course,
}
we do not do that to keep the code at
the user level unchanged.
Complexity is: Θ(1)
pf
pn Old bottom
Old top
&s node node
ps s
© Waleed A. Yousef 2008 14
/* Pre: The stack exists
Post: returns the number of elements*/
-All the space is reserved even the stack is -Extra field next for every new node.
empty (wasting memory)
-Stack gets full even if the memory is not! -The stack size is as large as the memory you have!
Then, there are advantages and disadvantages for every implementation. Which one is better really depends on
the application.E.g.,
If the memory is very limited, then may be the linked implementation is better.
The rule is: Know very well the pros and cons of each implementation and decide based on your application needs.
© Waleed A. Yousef 2008 19
References
•
Thanks