Skip to content

Commit ddf671d

Browse files
authored
Update stack_using_linked_lists.c
Added comments and time complexities.
1 parent 544f492 commit ddf671d

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed

data_structures/linked_list/stack_using_linked_lists.c

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -36,40 +36,40 @@ int main()
3636
}
3737
}
3838

39-
void push(struct node *p)
39+
void push(struct node *p) // push function will add a new node at the head of the list, time complexity O(1).
4040
{
4141
int item;
4242
struct node *temp;
43-
temp = (struct node *)malloc(sizeof(struct node));
43+
temp = (struct node *)malloc(sizeof(struct node)); //creating memory for temp node.
4444
printf("enter element to be inserted\n");
4545
scanf("%d", &item);
4646
temp->info = item;
4747

4848
temp->link = top;
49-
top = temp;
49+
top = temp; //top of the stack points to newly added node.
5050

5151
printf("inserted succesfully\n");
5252
}
53-
void pop(struct node *p)
53+
void pop(struct node *p) // pop function deletes the first node from the head, time complexity O(1).
5454
{
5555
int item;
5656
struct node *temp;
5757

58-
if (top == NULL)
58+
if (top == NULL) // Underflow condition
5959
printf("stack is empty\n");
6060
else
6161
{
6262
item = top->info;
6363
temp = top;
64-
top = top->link;
65-
free(temp);
64+
top = top->link; // new top will be the node pointed by previous top.
65+
free(temp); // free the memory of node using free().
6666
printf("Element popped is%d\n", item);
6767
}
6868
}
6969

7070
void display(struct node *p)
7171
{
72-
if (top == NULL)
72+
if (top == NULL) // Underflow condition
7373
printf("stack is empty\n");
7474
else
7575
{
@@ -79,6 +79,5 @@ void display(struct node *p)
7979
printf("%d\n", p->info);
8080
p = p->link;
8181
}
82-
// printf("%d\n",p->info);
8382
}
8483
}

0 commit comments

Comments
 (0)