#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
bool isSame(char ch,char arr){
if(ch=='('&&arr==')'||ch==')'&&arr=='(')
return true;
else if(ch=='{'&&arr=='}'||ch=='}'&&arr=='{')
return true;
else if(ch=='['&&arr==']'||ch==']'&&arr=='[')
return true;
else
return false;
}
bool Check(char *p){
stack <char> s;
for(int i=0;i<strlen(p);i++){
if(p[i]=='('||p[i]=='{'||p[i]=='['){
s.push(p[i]);
}
else if(p[i]==')'||p[i]=='}'||p[i]==']'){
if(s.empty())
return false;
char ch=s.top();
if(isSame(ch,p[i])){
s.pop();
}
else{
return false;
}
}
else{
continue;
}
}
if(s.empty())
return true;
else
return false;
}
int main()
{
char str[]="{A+(Q-T)+Z-M*(D+P)-Q/O}";
if(Check(str))
cout<<"Paranthesis is Balanced\n";
else
cout<<"Not Balanced\n";
return 0;
}
Sunday, 13 December 2015
Check Balanced Parenthesis in an Expression Using Stack API in C++
Reverse a string using Stack API in C++
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
void reverse(char *p);
int main()
{
char str[] = "Hello Bro !!";
reverse(str);
cout<<str;
return 0;
}
void reverse(char *p){
stack<char> s;
for(int i=0;i<strlen(p);i++){
s.push(p[i]);
}
for(int i=0;i<strlen(p);i++){
p[i]=s.top();
s.pop();
}
cout<<endl;
}
Reverse elements of a Doubly LinkedList in C
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node *next;
struct node *prev;
};
struct node *insert(struct node * head,int data){
printf("Entered insert\n");
struct node *newNode = (struct node *)malloc(sizeof(struct node));
struct node *temp = NULL;
temp = head;
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
printf("Node Allocated\n");
if(head==NULL){
printf("Entered if loop\n\n");
head = newNode;
printf("inside head insertion");
return head;
}
printf("above while loop \n");
while(temp->next!=NULL){
temp=temp->next;
}
newNode->prev=temp;
temp->next=newNode;
return head;
}
void print(struct node *head){
printf("Entered inside print function\n\n");
struct node *temp = head;
while(temp != NULL){
printf("%d\n",temp->data);
temp=temp->next;
}
}
struct node *reverse(struct node *head){
struct node *temp = NULL;
struct node *current = head;
while (current != NULL)
{
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev;
}
if(temp != NULL )
head = temp->prev;
return head;
}
int main()
{
struct node *head=NULL;
int i=0;
int num =0;
printf("Enter 10 numbers to insert into Doubly Linkedlist\n");
for(i=0;i<10;i++){
scanf("%d",&num);
head =insert(head,num);
printf("inserted the %d number , head -> data = %d",i,head->data);
}
printf("Linked List before Reverse\n");
print(head);
head=reverse(head);
printf("Linked List after Reverse\n");
print(head);
return 0;
}
Subscribe to:
Posts (Atom)