Completely Solved C, C++ Programs Assignment.




C program for implementation of a stack using the linked list

Filed Under: ,

Implementation of Stack using Linked List Initially the list is empty, so the top pointer is NULL. The push function takes a pointer to an existing list as the first parameter and a data value to be pushed as the second parameter, creates a new node by using the data value, and adds it to the top of the existing list. A pop function takes a pointer to an existing list as the first parameter, and a pointer to a data object in which the popped value is to be returned as a second parameter. Thus it retrieves the value of the node pointed to by the top pointer, takes the top point to the next node, and destroys the node that was pointed to by the top.
If this strategy is used for creating a stack with the previously used four data values: 10, 20, 30, and 40, then the stack is created as shown in Figure 2.
Program C program for implementation of a stack using the linked list
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *push(struct node *p, int value)
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
/* creates new node
using data value
passed as parameter */
if(temp==NULL)
{
printf("No Memory available Errorn");
exit(0);
}
temp->data = value;
temp->link = p;
p = temp;
return(p);
}

struct node *pop(struct node *p, int *value)
{
struct node *temp;
if(p==NULL)
{
printf(" The stack is empty can not pop Errorn");
exit(0);
}
*value = p->data;
temp = p;
p = p->link;
free(temp);
return(p);
}

void main()
{
struct node *top = NULL;
int n,value;
clrscr();
do
{
do
{
printf("Enter the element to be pushedn");
scanf("%d",&value);
top = push(top,value);
printf("Enter 1 to continuen");
scanf("%d",&n);
} while(n == 1);

printf("Enter 1 to pop an elementn");
scanf("%d",&n);
while( n == 1)
{
top = pop(top,&value);
printf("The value poped is %dn",value);
printf("Enter 1 to pop an elementn");
scanf("%d",&n);
}
printf("Enter 1 to continuen");
scanf("%d",&n);
} while(n == 1);
}
Output
Enter the element to be pushed
10
Enter 1 to continue
1
Enter the element to be pushed
20
Enter 1 to continue
0
Enter 1 to pop an element
1
The value popped is 20
Enter 1 to pop an element
1
The value poped is 10
Enter 1 to pop an element
0
Enter 1 to continue
1
Enter the element to be pushed
30
Enter 1 to continue
1
Enter the element to be pushed
40
Enter 1 to continue
0
Enter 1 to pop an element
1
The value popped is 40
Enter 1 to pop an element
0
Enter 1 to continue
1
Enter the element to be pushed
50
Enter 1 to continue
0
Enter 1 to pop an element
1
The value popped is 50
Enter 1 to pop an element
1
The value popped is 30
Enter 1 to pop an element
0
Enter 1 to continue
0
Back to main directory:  Data Structure 


Get Free Programming Tutorials and Solved assignments