Professional Documents
Culture Documents
3.2 Stacks Linked List Implementation
3.2 Stacks Linked List Implementation
Algorithm Analysis I
(Unit III – Session 2)
Dr.G.Anupriya
Professor - CSE Department
3
Stack
• Linear data structure
• Last In First Out (LIFO)
• List with the restriction that insertions and deletions can
only be performed at one end – called the top end of the
Stack
Book 5 Top of Stack
• Examples: Book 4
• Stack of coins / books Book 3
Book 2
• Undo / Redo operations
Book 1
Stack of Books
4
Stack Linked List implementation
• Push operation
Should we check for Stack
void push(int val) full condition? Justify..
{
struct Node *NN=(struct Node *)malloc(sizeof(struct Node));
NN->data = val;
NN->next = top;
top = NN;
} Time Complexity – O(1)
{
struct Node *NN=(struct Node *)malloc(sizeof(struct Node));
NN->data = val; Push 1
NN->next = top; NN
1
top = NN;
}
top
int pop()
temp top
{
if(top==NULL)
{ printf(“Stack Empty”); return -1; } Pop
int val = top->data;
val = 3
struct Node *temp = top;
top = top->next; return 3
free(temp);
return val;
}
int pop()
top temp
{
if(top==NULL)
{ printf(“Stack Empty”); return -1; } Pop
int val = top->data;
val = 1
struct Node *temp = top;
top = top->next; return 1
free(temp);
return val;
}
int top_val()
{ top
return 1
if(top==NULL)
{ printf(“Stack Empty”); return -1; }
return topdata;
} top=
return -1