Task 1
#include <bits/stdc++.h>
using namespace std;
bool Balanced(string expression)
{
stack<char> sentence;
char ch;
for (int n= 0; n < expression.length(); n++)
{
if (expression[n] == '(' || expression[n] == '['
|| expression[n] == '{')
{
sentence.push(expression[n]);
continue;
}
if (sentence.empty())
return false;
switch (expression[n]) {
case ')':
ch = sentence.top();
sentence.pop();
if (ch == '{' || ch == '[')
return false;
break;
case '}':
ch = sentence.top();
sentence.pop();
if (ch == '(' || ch == '[')
return false;
break;
case ']':
ch = sentence.top();
sentence.pop();
if (ch == '(' || ch == '{')
return false;
break;
}
}
return (sentence.empty());
}
// Testing code
int main()
{
string expression = "{()}[]";
if (Balanced(expression))
cout << "Balanced";
else
cout << "Not Balanced";
return 0;
}
Task 2
#include <iostream>
using namespace std;
class List {
public:
int data;
List* nextNode;
};
void pairWiseSwap(List* node)
{
List* tempNode = node;
while (tempNode != NULL && tempNode->nextNode != NULL) {
swap(tempNode->data,
tempNode->nextNode->data);
tempNode = tempNode->nextNode->nextNode;
}
}
void insert(List** node, int data)
{
List* newNode = new List();
newNode->data = data;
newNode->nextNode = (*node);
(*node) = newNode;
}
void displayList(List* head)
{
while (head != NULL) {
cout << head->data << " ";
head = head->nextNode;
}
}
int main()
{
List* startNode = NULL;
insert(&startNode, 5);
insert(&startNode, 4);
insert(&startNode, 3);
insert(&startNode, 2);
insert(&startNode, 1);
cout << "Before swapping the linked list\n";
displayList(startNode);
pairWiseSwap(startNode);
cout << "\nAfter swapping the linked list \n";
displayList(startNode);
return 0;
}
Comments
Leave a comment