Вы находитесь на странице: 1из 21

//recursion

/*Q2. Write the recursive function the reverse(char * s, int len). This function
takes a
string (pointer to char) and the length of the string as arguments and returns t
he same
string with its characters in the reverse order.
Sample Input
Simple
Sample Output (in the same input string s)
elpmiS*/
/*Q3. Write a function count_spaces(char *s) that counts the number of whitespac
e
characters that appear in a string. Characters are whitespace as defined by
the isspace() function in the ctype library. Write this function recursively.
Sample Input
Ahmed Ali Mohamed
Sample Output
2
Q4. A palindrome is a sequence of characters or numbers that looks the same forw
ards
and backwards. For example, "dad" is a palindrome because it is spelled the same
reading it from front to back as from back to front.
Write a function int ispalindrome(char * s, int len) that takes a string and it
s length as
arguments and recursively determines whether the string is a palindrome*/
/*Q6 Write a program to compute digital roots. The digital root of a number is t
he number
resulting from repeatedly summing the digits of the number until a single digit
is
reached. For example:
digitalRoot(5) = 5
digitalRoot(42) = 4 + 2 = 6
digitalRoot(137) = digitalRoot(1 + 3 + 7) = digitalRoot(11) = 2
#include<iostream>
#include <cstring>
using namespace std;
void reverse(char*s, int len)
{
if (len <= 0)
return;
char temp = s[0];
char temp2 = s[len - 2];
s[0] = temp2;
s[len - 2] = temp;
reverse(s+1, len - 2);
}
int countWhitespaces(char s[], int length)
{
if (length <= 0)
return 0;
if (s[0] == ' ')
return 1+countWhitespaces(s+1,length-1);
else
return countWhitespaces(s+1, length - 1);
}
bool isPal(char s[], int length)
{
if (length <= 1)
return true;

char o = s[0];
char l = s[length - 2];
if (o != l)
return false;
return isPal(s + 1, length - 2);
}
int DigRoots(int num)
{
if (num / 10 == 0)
{
return num;
}
return num % 10 + DigRoots(num / 10);
}
void main()
{
/*char k[] = "let's check it";
cout<<countWhitespaces(k, 15)<<endl;
char k[] = "mooonooom";
cout << isPal(k, 10) << endl;
cout << DigRoots(12345) << endl;
}
//sorting
/*In insertion sort, we scan back through the sorted portion of the list to dete
rmine
where the new value should be inserted. We shift all the scanned values downward
,
and insert the new value in the open location.
a. Modify the code to use binary search to find the appropriate insertion spot
rather than a linear scan, then insert the element?
b. Does this affect the overall time complexity of the algorithm? Why?
#include <iostream>
using namespace std;
int search(int arr[], int length,int value)
{
int start = 0, end = length - 1, mid;
while (start <= end)
{
mid = (start + end) / 2;
if (arr[mid] == value)
return mid;
else if (arr[mid]>value)
end = mid - 1;
else if (arr[mid] < value)
start = mid + 1;
}
return start;
}
void swap(int&a, int&b)
{
int temp = a;
a = b;
b = temp;
}
void InsertionWithBinary(int arr[], int length)
{
for (int i = 1; i < length; i++)
{

if (arr[i] < arr[i - 1])


{
int index = search(arr, i, arr[i]);
int j = i;
while (j > index)
{
swap(arr[j], arr[j - 1]);
j--;
}
}
}
}
Q3.Given two integer arrays of size N, design an algorithm to determine whether
one is
a permutation of the other.That is, do they contain exactly the same entries but
,
possibly, in a different order.
bool compare(int arr1[], int arr2[], int size)
{
InsertionWithBinary(arr1, size);
InsertionWithBinary(arr2, size);
for (int i = 0; i < size; i++)
{
if (arr1[i] != arr2[i])
return false;
}
return true;
}
void main()
{
int arr1[] = { 1, 3, 5, 7, 9, 9, 7, 5, 3, 1 };
int arr2[] = { 9, 7, 5, 3, 1, 9, 7, 5, 3, 1 };
cout << compare(arr1, arr2, 10);
}*/
//Linked Lists
/*Q2. Write a function to insert a node before a given node? It should take a va
lue ,the
head node and node as its parameters.
#include <iostream>
using namespace std;
struct Node
{
int data;
Node*next;
};
void InsertBefore(Node*&head, Node*g, int val)
{
if (head == g)
{
Node*tep = new Node;
tep->data = val;
tep->next = g;
head = tep;
}
else{
Node*o = head;
while (o->next != g)
{

o = o->next;
}
Node*tep = new Node;
tep->data = val;
tep->next = g;
o->next = tep;
}
}
/*Q3. Write a function to get the K
th
node from the start of a linked list. It counts from 0
here, so the 0
th
node from start is the head of list, It should take K and the head node as
its parameters.
Node* kth(Node*head, int k)
{
if (head == NULL)
return NULL;
else{
int count = 0;
while (count < k)
{
head = head->next;
count++;
}
return head;
}
}
/*Q4. Write a function to get the K
th
node from the end of a linked list. It counts from 0
here, so the 0
th
node from end is the tail of list, It should take K and the head node as its
parameters.
Node* backkth(Node*head, int k)
{
int count = 0;
Node*temp = head;
while (temp != NULL)
{
temp = temp->next;
count++;
}
int wanted = count - k;
count = 0;
while (count < wanted)
{
head = head->next;
count++;
}
return head;
}
/*Q5. Write a SortedInsert() function which takes a head node that is pointing t
o a sorted
list in increasing order and a value, inserts the node into the correct sorted p
osition in
the list.
void SortedInsert(Node*&h, int value)

{
Node* t = new Node;
t->data = value;
if (h == NULL)
{
t->next = NULL;
h = t;
}
else if (h->next == NULL)
{
if (h->data > value)
{
t->next = h;
h = t;
}
else{
t->next = NULL;
h->next = t;
}
return;
}
Node*e = h;
while (e->next!=NULL&&e->data < value)
{
e = e->next;
}
t->next = e->next;
}
int countDuplicates(Node*t)
{
int count = 0;
int dat = t->data;
while (t->data == dat)
{
count++;
t = t->next;
}
return count;
}
/*Q6. Write a RemoveDuplicates() function which takes a head node that is point
ing to a
sorted list in increasing order and deletes any duplicate nodes from the list. I
deally, the
list should only be traversed once.
void remove(Node*h){
Node*t = h;
t->data = h->data;
Node*t1 = h;
if (h->next == NULL)
return;
if (h == NULL)
return;
while (t->next != NULL){
if (t->data == t->next->data)
{
t1 = t->next;
t->next = t1->next;

delete t1;
}
else
t = t->next;
}
}
void RemoveDuplicates(Node*head)
{
if (head == NULL)
return;
else
{
while (head!= NULL&&head->next != NULL)
{
int val = head->data;
Node*temp = head->next;
while (temp!=NULL&&temp->data == val)
{
Node*i = temp;
temp = temp->next;
delete i;
}
Node*t = head;
t->next=temp;
head = temp;
}
}
}
void insertFront(Node*&h,int k)
{
Node*p = new Node;
p->data = k;
if (h == NULL)
{
p->next = NULL;
h = p;
}
else
{
p->next = h;
h = p;
}
}
void print(Node*h)
{
while (h != NULL)
{
cout << h->data << endl;
h = h->next;
}
}
void main()
{
Node*h = NULL;
insertFront(h, 3);
insertFront(h, 3);
insertFront(h, 2);
insertFront(h, 2);
insertFront(h, 1);

insertFront(h, 1);
RemoveDuplicates(h);
print(h);
}*/
//Stacks
/*Q1. Given an expression string exp, write a program to examine whether the pai
rs and
the orders of { , } , ( , ) , [ , ] are correct in exp
Test :
Input : [()]{}{[()()]()}
Output : True
Input : [(])
Output : false*/
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool isup(char a)
{
if (a == '[' || a =='('|| a== '{')
return true;
return false;
}
bool isdown(char a)
{
if (a == ']' || a == ')' || a == '}')
return true;
return false;
}
bool examine(char up, char down)
{
if (up == '('&&down == ')' || up == '['&&down == ']' || up == '{'&&down
== '}')
return true;
return false;
}
bool check(string h)
{
stack<char>up;
for (int i = 0; i < h.size(); i++)
{
if (isup(h[i]))
up.push(h[i]);
else if (isdown(h[i]))
{
char u = up.top();
up.pop();
if (!examine(u, h[i]))
return false;
}
}
if (!up.empty())
return false;
return true;
}
//Q2. Given a string, Write a function to reverse it using stack.

void reverse(string x)
{
stack<char>rev;
for (int i = 0; i < x.size(); i++)
{
rev.push(x[i]);
}
for (int i = 0; i < x.size(); i++)
{
x[i] = rev.top();
rev.pop();
}
}
//Q3. Write a recursive function to print the stack contents in reverse order wi
thout
//changing stack contents
void prtrev(stack<int>st)
{
if (st.empty())
return;
int x = st.top();
st.pop();
cout << x << endl;
prtrev(st);
st.push(x);
}
/*Q5. Write a function to evaluate a postfix expression using stack.
Test
Input :
231*+9-Output :
-4*/
int chartodig(char a)
{
switch (a)
{
case '1':
return 1;
break;
case '2':
return 2;
break;
case '3':
return 3;
break;
case '4':
return 4;
break;
case '5':
return 5;
break;
case '6':
return 6;
break;
case '7':
return 7;
break;
case '8':
return 8;
break;

case '9':
return 9;
break;
}
}
int calc(int a, int b, char c)
{
switch (c)
{
case '+':
return a + b;
break;
case '-':
return a - b;
break;
case '*':
return a * b;
break;
case '/':
return a / b;
break;
}
}
int evaluate(string exp)
{
stack<int>nums;
for (int i = 0; i < exp.size(); i++)
{
if (isdigit(exp[i]))
{
int t = chartodig(exp[i]);
nums.push(t);
}
else
{
int one = nums.top();
nums.pop();
int two = nums.top();
nums.pop();
int res = calc(one,two, exp[i]);
nums.push(res);
}
}
int a = nums.top();
nums.pop();
return a;
}
/*Q6. Given an array, Write a program to print the Next Greater Element (NGE) fo
r every
element. The Next greater Element for an element x is the first greater element
on the
right side of x in array. Elements for which no greater element exist, consider
next
greater element as -1, Solution should be O(N).
void NGE(int arr[],int size)
{
stack<int>st;
stack<int>st2;
st.push(arr[0]);
for (int i = 1; i < size; i++)

{
int t = st.top();
while ((!st.empty())&&arr[i]>t)
{
t = st.top();
st2.push(t);
st.pop();
}
while (!st2.empty())
{
int y = st2.top();
st2.pop();
cout << y << "------>" << arr[i] << endl;
}
st.push(arr[i]);
}
while (!st.empty())
{
int t = st.top();
cout << t << "----->" << -1 << endl;
st.pop();
}
}
void main()
{
int arr[] = { 2, 5, 8, 4, 97 };
NGE(arr, 5);
}*/
//queues
/*Q3.Implement a queue of integers using linked list supporting the following
functionalities :
1-void enqueue(queue * q, int value).
2. int dequeue(queue * q).
3. int getsize(queue * q).
4. bool isempty(queue * q).*/
/*Q1. Write a linear-time algorithm for reversing a queue Q. To access the queue
, you are
only allowed to use the methods of queue ADT (enqueue, dequeue) . Hint: Consider
using an auxiliary data structure.
#include <iostream>
#include <string>
#include <stack>
using namespace std;
struct Node
{
int data;
Node*next;
};
struct queue
{
int size=0;
Node*head;
Node*tail;
};
void enqueue(queue * q, int value)

{
q->size++;
Node*p = new Node;
p->data = value;
if (q->head == NULL)
{
p->next = NULL;
q->head = p;
q->tail = p;
}
else if (q->head->next == NULL)
{
q->head->next = p;
q->tail = p;
}
else
{
Node*temptail = q->tail;
p->next = NULL;
temptail->next = p;
q->tail = p;
}
}
int dequeue(queue*q)
{
if (q->head == NULL)
{
return NULL;
}
else
{
q->size--;
Node*temp = q->head;
q->head = q->head->next;
return temp->data;
}
}
int getSize(queue*q)
{
return q->size;
}
bool isEmpty(queue*q)
{
if (q->size == 0)
return true;
return false;
}
void reverse(queue*q)
{
stack<int>st;
while (!isEmpty(q))
{
int t = dequeue(q);
st.push(t);
}
while (!st.empty())
{
int t =st.top();
st.pop();
enqueue(q, t);

}
}
void print(queue*q)
{
while (!isEmpty(q))
{
cout << dequeue(q)<<endl;
}
}
/*Q2.Implement a queue using two stacks, what is the complexity of enqueue and
dequeue of that implementation
struct QuStk
{
int size = 0;
stack<int>in;
stack<int>out;
};
void QuStkInto(QuStk*q,int val)
{
q->size++;
q->in.push(val);
}
int QuStkOut(QuStk*q)
{
if (q->in.empty&&q->out.empty)
return NULL;
else
{
if (q->out.empty)
{
while (!q->in.empty)
{
int t = q->in.top();
q->in.pop();
q->out.push(t);
}
}
int a = q->out.top();
q->out.pop();
return a;
}
}
void main()
{
queue qu;
queue*q = &qu;
q->head = NULL;
q->tail = NULL;
enqueue(q, 1);
enqueue(q, 1);
enqueue(q, 2);
enqueue(q, 2);
enqueue(q, 3);
enqueue(q, 3);
reverse(q);
print(q);
}*/
//Trees

/*
#include <iostream>
#include<queue>
using namespace std;
struct TreeNode
{
TreeNode*left;
TreeNode* right;
int data;
};
TreeNode* createNode(int val)
{
TreeNode*t = new TreeNode;
t->left = NULL;
t->right = NULL;
t->data = val;
return t;
}
int size(TreeNode*t)
{
if (t == NULL)
return 0;
int left = size(t->left);
int right = size(t->right);
return 1 + left + right;
}
int countleaf(TreeNode*t)
{
if (t == NULL)
return 0;
else
{
if (t->left == NULL&&t->right == NULL)
return 1;
int left = countleaf(t->left);
int right = countleaf(t->right);
return left + right;
}
}
int min(TreeNode*t)
{
if (t == NULL)
return INT_MAX;
else
{
int min1 = t->data;
int minL = min(t->left);
int minR = min(t->right);
int min = (minL < minR) ? minL : minR;
min = (min < min1) ? min : min1;
return min;
}
}
int max(TreeNode*t)
{
if (t == NULL)
return INT_MIN;
else
{
int max1 = t->data;

int maxL = max(t->left);


int maxR = max(t->right);
int max = (maxL >maxR) ? maxL : maxR;
max = (max > max1) ? max : max1;
return max;
}
}
bool isbst(TreeNode*t)
{
if (t == NULL)
return true;
if ((t->data<max(t->left)) || (t->data>min(t->right)))
return false;
return t->left&&t->right;
}
int minHeight(TreeNode*t)
{
if (t == NULL)
return 0;
int left = 1 + minHeight(t->left);
int right = 1 + minHeight(t->right);
return(left < right) ? left : right;
}
bool same(TreeNode*m, TreeNode*t)
{
if (m == NULL&&t == NULL||m==t)
return true;
if (m == NULL&&t != NULL || m != NULL&&t == NULL)
return false;
if (m->data != t->data)
return false;
return same(m->left, t->left) && same(m->right, t->right);
}
/*Q2. Write a C function to count nodes that have only one child
int onechild(TreeNode*t)
{
if (t == NULL)
return 0;
else
{
if (t->left == NULL&&t->right != NULL || t->left != NULL&&t->rig
ht == NULL)
return 1 + onechild(t->left) + onechild(t->right);
else
return onechild(t->left) + onechild(t->right);
}
}
/*Q7. Write a C function to sort an array using a binary search tree.
void helper(queue<int>&q, TreeNode*r)
{
if (r == NULL)
return;
helper(q, r->left);
q.push(r->data);
helper(q,r->right);
}
void sortbybst(int*x,TreeNode*r, int size)
{
queue<int> q;

int i = 0;
helper(q, r);
while (!q.empty())
{
x[i++] = q.front();
q.pop();
}
}
/*Q8. Given two values k1 and k2 (where k1 < k2) and a root pointer to a Binary
Search Tree. Print all the keys of tree in range k1 to k2.
void prtRange(TreeNode*t, int k1, int k2)
{
if (t == NULL)
return;
if (t->data<k2)
prtRange(t->left,k1, k2);
if (t->data<k2&&t->data>k1)
cout << t->data << endl;
if (t->data < k2)
prtRange(t->right,k1,k2);
}
/*Q9.Write a c function to get the in order successor of a given tree node. Note
that the in
order successor of a given tree node is the smallest element in the right sub tr
ee of that
given node. */
/*TreeNode* help(TreeNode*t)
{
if (t == NULL)
return NULL;
if (t->left == NULL)
return t;
return(t->left);
}
TreeNode* succ(TreeNode*t)
{
if (t == NULL)
return NULL;
return help(t->right);
}
/*Implement the following functionalities and write
.
? Insert in a binary search tree.
function prototype -> void insert(TreeNode * root,
? search in a binary search tree.
function prototype -> TreeNode * search(TreeNode *
? delete a value from a binary search tree
function prototype -> TreeNode * delete(TreeNode *
void insert(TreeNode*&t, int value)
{
TreeNode*m = new TreeNode;
m->data = value;
m->left = NULL;
m->right = NULL;
if (t == NULL)
{

the main function to test it


int value)
root, int value)
root, int value

t = m;
return;
}
else
{
if (t->data > value)
{
if (t->left == NULL)
t->left = m;
else insert(t->left, value);
}
if (t->data < value)
{
if (t->right == NULL)
t->right = m;
else insert(t->right, value);
}
}
}
TreeNode * search(TreeNode * t, int value)
{
if (t == NULL)
return NULL;
else
{
if (t->data == value)
return t;
if (t->data > value)
{
search(t->left, value);
}
else if (t->data < value)
{
search(t->right, value);
}
}
}
void Del(TreeNode*t, int value)
{
if (t == NULL)
return;
else
{
if (t->left->data == value)
{
if (t->left->left == NULL&&t->left->right == NULL)
t->left = NULL;
else if(t->left->left != NULL&&t->left->right == NULL)
{
TreeNode*temp = t->left->left;
t->left->data = temp->data;
t->left->left = NULL;
}
else if (t->left->left == NULL&&t->left->right != NULL)
{
TreeNode*temp = t->left->right;
t->left->data = temp->data;
t->left->right = NULL;
}

else if (t->left->left != NULL&&t->left->right != NULL)


{
TreeNode*r = succ(t->left);
t->left->data = r->data;
TreeNode*tt = t->right;
while (tt->left != NULL&&tt->left != r)
{
tt = tt->left;
}
tt->left = NULL;
}
}
else
{

if (t->right->data == value)
if (t->right->left == NULL&&t->right->right == NULL)
t->right = NULL;
else if (t->right->left != NULL&&t->left->right == NULL)
{
TreeNode*temp = t->right->left;
t->right->data = temp->data;
t->right->left = NULL;
}
else if (t->left->left == NULL&&t->left->right != NULL)
{
TreeNode*temp = t->right->right;
t->right->data = temp->data;
t->right->right = NULL;
}
else if (t->right->left != NULL&&t->right->right != NULL

)
{
TreeNode*r = succ(t->right);
t->right->data = r->data;
TreeNode*tt = t->right;
while (tt->left != NULL&&tt->left != r)
{
tt = tt->left;
}
tt->left = NULL;
}
}
else if (t->data == value)
{
TreeNode*temp = succ(t);
t->data = temp->data;
TreeNode*s = t->right;
while (s != NULL && s->left != temp)
{
s = s->left;
}
s->left = NULL;
}
else
{
if (t->data > value)
{
Del(t->left, value);
}

else if (t->data < value)


{
Del(t->right, value);
}
}
}
}
void main()
{
TreeNode* root = NULL, *m = NULL;
insert(root, 5);
insert(root, 2);
insert(root, 7);
insert(root, 0);
insert(root, 4);
insert(root, 1);
insert(root, -1);
insert(root,3);
insert(root, 6);
insert(root, 9);
insert(root, 10);
insert(root, 8);
cout << "Size = " << size(root) << endl; // expected 12
cout << "leafs = " << countleaf(root) << endl; // expected 6
cout << "Is Binary Search Tree = " << isbst(root) << endl; // expected
1
cout << "MinTreedepth = " << minHeight(root) << endl; // expected 3
cout << "min = " << min(root) << endl; // expected -1
cout << "max = " << max(root) << endl; // expected 10
cout << "Number of Nodes that have only one child is " << onechild(root)
<< endl;
//createNode a tree
insert(m, 5);
insert(m, 2);
insert(m, 7);
insert(m, 0);
insert(m, 4);
insert(m, 1);
insert(m, -1);
insert(m, 3);
insert(m, 6);
insert(m, 9);
insert(m, 10);
insert(m, 7);
insert(m, 8);
insert(m, 12);
// note that this node is different than its corresponding node in root
tree
cout << "Number of Nodes that have only one child is " << onechild(m) <<
endl;
cout << "Both Trees Are the same ? = " << same(root, m) << endl; //expec
ted 0
TreeNode*n = search(m,9);
cout << "max = " << max(n) << endl;
}*/
//heaps

/*Q2. Write a C function to check whether a given array is heap or not.*/


#include <iostream>
using namespace std;
struct heap
{
int*arr;
int capacity;
int size;
};
heap* createheap(int capacity)
{
heap*m = new heap;
m->size = 0;
m->capacity = capacity;
m->arr = new int[capacity];
return m;
}
bool isHeap(heap*h)
{
if (h == NULL)
return true;
int i = 0;
int left;
int right;
while (i < h->size)
{
left = 2 * i + 1;
right = 2 * i + 2;
if (right < h->size)
{
if (h->arr[left] > h->arr[i] || h->arr[right] > h->arr[i
])
return false;
}
else if (left< h->size)
{
if (h->arr[left] > h->arr[i])
return false;
}
i++;
}
return true;
}
/*Q3. Given a heap write down two functions to return the maximum and minimum
values*/
int getMax(heap*h)
{
return h->arr[0];
}
int getmin(heap*h)
{
int n = h->size - 1;
int lastparent = (n - 1) / 2;
int min = INT_MAX;
for (int i = lastparent; i < n; i++)
{
if (h->arr[i] < min)
min = h->arr[i];
}

return min;
}
void swap(int&a, int&b)
{
int temp = a;
a = b;
b = temp;
}
void insert(heap*h, int k)
{
int i = h->size;
h->arr[h->size++]=k;
int parent;
while (i > 0)
{
parent = (i - 1) / 2;
if (h->arr[i] > h->arr[parent])
swap(h->arr[i], h->arr[parent]);
i = parent;
}
}
int removemax(heap*h)
{
if (h->size == 0)
return INT_MIN;
else
{
int max = h->arr[0];
h->size--;
int n = h->size;
int key = h->arr[h->size];
h->arr[0] = key;
int i = 0;
while (i < n)
{
int left = 2 * i + 1;
int right = 2 * i + 2;
if (right < n)
{
if (h->arr[right] >= h->arr[left])
{
if (h->arr[i] < h->arr[right])
{
swap(h->arr[i], h->arr[right]);
i = right;
}
else break;
}
else if (h->arr[right] <h->arr[left])
{
if (h->arr[i] < h->arr[left])
{
swap(h->arr[i], h->arr[l
eft]);
i = left;
}
else break;
}

}
else if (left < n)
{
if (h->arr[i] < h->arr[left])
{
swap(h->arr[i], h->arr[left]);
i = left;
}
else break;
}
else
break;
}
return max;}
}
void main()
{
heap * m = createheap(1000);
int * u = new int[10];
bool test = true;
while (test)
{
cout << "UNSorted Array: " << endl;
for (int i = 0; i<10; i++)
{
u[i] = rand() % 100;
cout << u[i] << " ";
insert(m, u[i]);
}
cout << endl << "min is " << getmin(m) << endl;
cout << "Sorted Array: " << endl;
for (int i = 0; i< 10; i++)
{
u[i] = removemax(m);
cout << u[i] << " ";
if (i>0 && u[i]>u[i - 1])
{
test = false;
cout << "error";
break;
}
}
cout << endl;
}
}

Вам также может понравиться