Uploaded by Zarar Azwar Khalid

assignment 6

advertisement
Issue Date:
18-11-2019
25-11-2019
Registration#
18-CS-53
Mehreen Fatima
18-CS-28
Zarar Azwar Khalid
Department of Computer Science, University of Engineering
1|Page
Q.1:Implent the Stack in linked list.
Sol:
Push():
Module:
1. void stack::push(){
2.
struct node* temp2;
3.
struct node* temp1;
4.
temp1=head;
5.
struct node* temp=(struct node*)malloc(sizeof(struct node));
6.
temp->data=d;
7.
if(temp1==NULL){
8.
temp->next=NULL;
9.
head=temp;
10.
}
11.
else{
12.
while(temp1->next!=NULL){
13.
temp1=temp1->next;
14.
}
15.
temp1->next=temp;
16.
temp->next=NULL;
17.
}
18. }
Output:
2|Page
Pop():
Module:
1. void stack::pop(){
2.
struct node* ptr;
3.
struct node* ptr1;
4.
ptr1=NULL;
5.
ptr=head;
6.
if(ptr==NULL){
7.
cout<<"Linked list is empty! ";
8.
}
9.
else{
10.
while(ptr->next!=NULL){
11.
ptr1=ptr;
12.
ptr=ptr->next;
13.
}
14.
ptr1->next=NULL;
15.
}
16. }
Output:
3|Page
Q2:Implement the infix to postfix and solution of infix through stacks:
Sol:
Solution of infix:
1. void polish::solution(){
2.
int a,b;
3.
int ans=0;
4.
int length=strlen(equation);
5.
char num[10]={'0','1','2','3','4','5','6','7','8','9'};
6.
int j=0;
7.
for(int i=0;i<length;i++){
8.
if(equation[i]=='0'||equation[i]=='1'||equation[i]=='2'||equation
[i]=='3'||equation[i]=='4'||equation[i]=='5'||equation[i]=='6'
||equation[i]=='7'||equation[i]=='8'||equation[i]=='9'){
9.
while(equation[i]!=num[j]){
10.
j++;
11.
}
12.
push(j);
13.
}
14.
else if(equation[i]=='+'||equation[i]=='*'||equation[i]
=='-'||equation[i]=='/'){
15.
a=pop();
16.
b=pop();
17.
if(equation[i]=='+'){
18.
ans=a+b;
19.
}
20.
if(equation[i]=='-'){
21.
ans=a-b;
22.
}
23.
if(equation[i]=='*'){
24.
ans=a*b;
25.
}
26.
if(equation[i]=='/'){
27.
ans=a/b;
28.
}
29.
push(ans);
30.
}
31.
}
32.
result(ans);
33. }
Push data:
Pop data:
4|Page
1. void polish::push(int s){
2.
stack[top]=s;
3.
top++;
4. }
1. int polish::pop(){
2.
top--;
3.
int a=stack[top];
4.
return a;
5. }
6.
Output:
5|Page
6|Page
Download