Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

1)some advantages of linked lists over arrays have already been mentioned.

However, there
are occasions when arrays have advantages over linked list. When are arrays preferable?

ANSWER:
Linked lists have following drawbacks:
a) Random access is not allowed. We have to access elements sequentially starting from the
first node. So we cannot do binary search with linked lists.
b) Extra memory space for a pointer is required with each element of the list.
c) Arrays have better cache locality that can make a pretty big difference in performance.

2)Given the following Node definition for a singly linked list


Struct Node{
int data;
Node *next=NULL;
} list=NULL;
Answer the following questions
A. Write a function that inserts in the front
B. Write a function that inserts in the end
C. Write a function that inserts after the nth element
D. Write a function that deletes all elements that has data=item
E. Write a function that deletes nth element
F. Write a function that appends list2 to list1

SOLUTION
A.
void insertfront(){
temp=new node;
cout<<"Enter datat ";
cin>>temp->data
temp->next=head;
head=temp;
}
B.
void insertlast(){
node *temp2=head;
temp=new node;
cout<<"Enter data "<<endl;
cin>>temp->data;
while(temp2->next!=NULL)
{
temp2=temp2->next;
}
temp2->next=temp;
}
C.
void insertanyposition(node *temp, int n){
temp=new node;
cin>>temp->data;
cout<<"where do you want to add "<<temp->data<<"?";
cin>>n;
if(n==1){
temp->next=head;
head=temp;
}
else{
Node *temp2=head;
for(int i=0;i<n-2;i++){
temp2=temp2->next;
}
temp->next=temp2->next;
temp2->next=temp;
temp=head;
}
}
D.//optional
// C++ Program to delete all occurrences of a given key in linked list
#include <iostream>
Using namespace std;
// A linked list node
structnode
{
Int data;
structnode *next;
};

/* Given a reference (pointer to pointer) to the head of a list


and an int, inserts a new node on the front of the list. */
Void push(struct node * *head_ref,int new_data)
{
Struct node *temp;
temp=new node;
temp->data = new_data;
temp->next = (*head_ref);
(*head_ref) = temp;
}

/* Given a reference (pointer to pointer) to the head of a list and


a key, deletes all occurrence of the given key in linked list */
Void deleteKey(struct node * *head_ref,int key)
{
// Store head node
Struct node* temp2 = *head_ref, *prev;

// If head node itself holds the key or multiple occurrences of key


while(temp2 != NULL && temp2->data == key)
{
head_ref = temp->next; // Changed head
Delete temp; // free old head
temp = head_ref; // Change Temp
}

// Delete occurrences other than head


while(temp2 != NULL)
{
// Search for the key to be deleted, keep track of the
// previous node as we need to change 'prev->next'
while(temp != NULL && temp->data != key)
{
prev = temp2;
temp2 = temp2->next;
}

// If key was not present in linked list


if(temp2 == NULL)return;

// Unlink the node from linked list


prev->next = temp2->next;

delete temp; // Free memory

//Update Temp for next iteration of outer loop


temp2 = prev->next;
}
}

// This function prints contents of linked list starting from


// the given node
Void displayList(struct node *node)
{
while(node != NULL)
{
cout<<node->data;
node = node->next;
}
}

/* Drier program to test above functions*/


Int main()
{
/* Start with the empty list */
Struct node* head = NULL;

push(&head, 7);
push(&head, 2);
push(&head, 3);
push(&head, 2);
push(&head, 8);
push(&head, 1);
push(&head, 2);
push(&head, 2);

Int key = 2;// key to delete


cout<<"Created Linked List: ";
cout<<head;

deleteKey(&head, key);
Cout<<"\nLinked List after Deletion of 1: ";

cout<<head;
return0;
}
Output:
Created Linked List:
2 2 1 8 2 3 2 7
Linked List after Deletion of 1:
1 8 3 7
E.
void deleteanyp(int n){
temp=head;
if(head==NULL){
cout<<"LIST IS EMPTY!"<<endl<<endl;
}
else{
cout<<" delete data u want "<<endl<<endl<<endl;
cout<<" Enter the position of the student you want to delete ";
cin>>n;
cout<<endl<<endl;
if(n==1){
head=temp->next;
cout<<temp->data<<" is deleted successfully!"<<endl<<endl;
delete temp;
}
else{
temp2=head;
for(int i=0;i<n-2;i++){
temp=temp->next;
}
temp2=temp->next;
temp->next=temp2->next;
cout<<temp2->data<<" is deleted successfully!"<<endl<<endl;
delete temp2;

}
}
}
F.//optional
void Append(struct node** aRef, struct node** bRef) {
struct node* current;
if (*aRef == NULL) { // Special case if a is empty
*aRef = *bRef;
}
else { // Otherwise, find the end of a, and append b there
current = *aRef;
while (current->next != NULL) { // find the last node
current = current->next;
}
current->next = *bRef; // hang the b list off the last node
}
*bRef=NULL; // NULL the original b, since it has been appended above
}
3)What is the major difference of stack and queue?

ANSWER:
In high level programming,
a stack is defined as a list or sequence of elements that is lengthened by placing new
elements "on top" of existing elements and shortened by removing elements from the top of
existing elements. It is an ADT[Abstract Data Type] with math operations of "push" and
"pop".
A queue is a sequence of elements that is added to by placing the new element at the rear of
existing and shortened by removing elements in front of queue. It is an ADT[Abstract Data
Type]. There is more to these terms understood in programming of Java, C++, Python and
so on.

4)Implement stack using linked list.

SOLUTION
struct node{
int data;
node *next;
};
struct node *temp,*temp2,*top=NULL;
void push();
void pop();
void displayList();
/////////////////////////
void push(){
temp=new node;
temp2=top;
cout<<"enter data ";
cin>>temp->data;
cout<<temp->data<<" is added"<<endl;
temp->next=NULL;
if(top==NULL){
top=temp;
}
else{
temp->next=top;
top=temp;
}
}
void pop(){
if(top==NULL){
cout<<"stack is empty"<<endl;
}
else{
temp=top;
top=top->next;
cout<<temp->data<<" is deleted"<<endl;
delete temp;
}
}
void displayList(){
temp=top;
if(top==NULL){
cout<<"stack is empty"<<endl<<endl;
}
else{
while(temp!=NULL){
cout<<temp->data<<endl;
temp=temp->next;
}
}
}
5)write a program to reverse string(character array) using a stack.

SOLUTION
#include<iostream>
#include<cstring>

using namespace std;

int max=100;

int top,stack[max];

void push(char x){

//push(inserting element in stack) operation


if(top==max-1){
cout<<”stack overflow”;
}
else{
stack[++top]=x;
}
void pop(){
//pop(removing element from stack)
cout<<stack[top--];
}
int main(){
char str[]=”datastructure”;
int len=strlen(str),i;
For(i=0;i<len;i++){
Push(str[i]);
}
For(i=0;i<len;i++){
Pop();
}
return 0;
}
6)Write a code to implement circular queue(all operations i.e enqueue(),display() and
dequeue() operations).

SOLUTION
//enqueue
void insert()
{
if(rear==(Max-1)&& front==-1)
{
cout<<"queue is full"<<endl;
}
else if(rear==(Max-1)&&front>=0){
rear=0;}
else{
cout<<"enter the element to add"<<endl;
cin>>data;
rear=rear+1;
queue[rear]=data;
cout<<"'"<<queue[rear]<<"'"" is added to the queue"<<endl;
if(front==(Max-1))
{
cout<<"queue is full!!"<<endl<<endl; }
}
}
//dequeue

void del()
{
if(front==-1&&rear==-1)
{
cout<<"queue is empty"<<endl<<endl;;
}
else {
if(front==rear){
front=-1;
rear=-1;
}
else if(front==(Max-1)){
front=0;
}
else{
front=front+1;
}
cout<<queue[front]<<" is removed from queue"<<endl;
}
menu();
}
// Display Circular Queue

void display()
{
int front_pos = front, rear_pos = rear;
if (front == -1)
{
cout<<"Queue is empty\n";
return;
}
else{
cout<<"Queue elements :\n";
if (front_pos <= rear_pos)
{
while (front_pos <= rear_pos)
{
cout<<cqueue_arr[front_pos]<<" ";
front_pos++;
}
}
else
{
while (front_pos <= MAX - 1)
{
cout<<cqueue_arr[front_pos]<<" ";
front_pos++;
}
front_pos = 0;
while (front_pos <= rear_pos)
{
cout<<cqueue_arr[front_pos]<<" ";
front_pos++;
}
}
cout<<endl;
}
}
7)List the application of tree with example.

ANSWER:
In windows go to command line and type tree. You can see the folder tree structure.
Linux file system is also a tree.

HTML Document Object Model (DOM):


All html text,attributes are stored in tree called Document Object Model (DOM).
Network Routing :

Syntax Tree in Compiler :


In compiler , every expression is converted into syntax tree format.
Auto correcter and spell checker :

Next Move in games:


In Artificial intelligence game (opponent is cpu) , next moves are stored using tree data
structure.
8)What is recursion?
ANSWER:
Recursion is a method where the solution to a problem depends on solutions to smaller
instances of the same problem (as opposed to iteration).
The approach can be applied to many types of problems, and recursion is one of the central
ideas of computer science.

9)Write recursive function insertEnd to insert element at the end of linked list.

SOLUTION:
Struct Node{
int data;
Node *next=NULL;
};
void insertEnd();

void inserteEnd(){
node *temp2=head;
Node *temp=new node;
cout<<"Enter data "<<endl;
cin>>temp->data;
while(temp2->next!=NULL)
{
temp2=temp2->next;
}
temp2->next=temp;
}
10)Define the following terms; support answer with appropriate example
Double ended queue:- In computer science, a double-ended queue (dequeue, often
abbreviated to deque, pronounced deck) is an abstract data type that generalizes a queue,
for which elements can be added to or removed from either the front (head) or back (tail).It
is also often called a head-tail linked list, though properly this refers to a specific data
structureimplementation of a deque
Deque examples
Deque1 - Construction, enumeration, access, pushing, popping.
Deque2 - Counting, finding, erasing, replacing, removing.
Deque3 - Insertion.
Deque4 - Exceptions.
B)Priority queue:- A priority queue is an abstract data type which is like a regular queue or
stack data structure, but where additionally each element has a "priority" associated with
it. In a priority queue, an element with high priority is served before an element with low
priority. If two elements have the same priority, they are served according to their order in
the queue.
While priority queues are often implemented with heaps, they are conceptually distinct
from heaps. A priority queue is an abstract concept like "a list" or "a map"; just as a list
can be implemented with a linked list or an array, a priority queue can be implemented with
a heap or a variety of other methods such as an unordered array.
PriorityQueue example
PriorityQueue1 - Construction, enumeration, pushing, popping.
D)Binary tree:- A binary tree is a tree data structure in which each node has at most two
children, which are referred to as the left childand the right child. A recursive definition
using just set theory notions is that a (non-empty) binary tree is a triple (L, S, R), where L
and R are binary trees or the empty set and S is a singleton set. Some authors allow the
binary tree to be the empty set as well.
Examples of binary trees
E)Binary search tree:-In computer science, binary search trees (BST), sometimes called
ordered or sorted binary trees, are a particular type ofcontainers: data structures that store
"items" (such as numbers, names etc.) in memory. They allow fast lookup, addition and
removal of items, and can be used to implement either dynamic sets of items, or lookup
tables that allow finding an item by its key (e.g., finding the phone number of a person by
name).

Following is a pictorial representation of BST −


F,G) Definition:a binary tree T is full if
each node is either a leaf or
possesses exactly two child
Nodes.
A full binary tree (sometimes proper binary tree or 2-tree) is a tree in which every node

other than the leaves has two children.

Definition: a binary tree T with n


levels is complete if all
levels except possibly the
last are completely full,
and the last level has all its
nodes to the left side.
A complete binary tree is a binary tree in which every level, except possibly the last, is
completely filled, and all nodes are as far left as possible.

H)Level of binary tree:-A binary tree is one where each node has, at most, 2 children,
creatively named left and right. We define the level of a tree as the number of parent nodes a
tree node has. The root of the tree, therefore, is at level 0. Root's children are at level 1, etc.
In general, each level of a binary tree can have, at most, 2N nodes, where N is the level of the
tree. To be counted as a level, the level must have at least one non-null node. The maximum
level of the tree is the last such level.
As an example, consider the tree:
A
/ \
1 2
/\ \
3 4 C
\
D

At level 2, the tree has the elements 3, 4, and C. The maximum level of the tree is 3.
I)Depth of binary tree:-The depth of a node is the number of edges from the root to the
node.

A binary Tree with depth 4

11)Write the full code to implement binary search tree


12)Give code segment for inorder, preorder and postorder traversal.

SOLUTION:
#include<iostream>
using namespace std;
struct BST{
int value;
BST *left;
BST *right;
};
BST *root=NULL;
void inorder(BST *temp);
void preorder(BST *temp);
void postorder(BST *temp);
bool search(BST *temp,int v);
struct BST *insert(BST *temp,int v);
int main(){
int n,d,v;
cout<<"enter number of nodes ";
cin>>n;
for(int i=0;i<n;i++){
cout<<i+1<<":";
cout<<"enter value ";
cin>>d;
root=insert(root,d);
}
cout<<endl<<endl;
cout<<"inorder"<<endl<<endl;
inorder(root);
cout<<endl<<endl;
cout<<"preorder "<<endl<<endl;
preorder(root);
cout<<endl<<endl;
cout<<"================================"<<endl<<endl;
cout<<"postorder"<<endl<<endl;
postorder(root);
cout<<endl<<endl;
cout<<"================================"<<endl<<endl;
cout<<"enter the value do you want to search ";
cin>>v;
int flag=search(root,v);
if(flag==1){
cout<<v<<" is found"<<endl;
}
else{
cout<<v<<" is not found"<<endl;
}
}
struct BST *insert(BST *temp,int v){
if(temp==NULL){
temp=new BST;
temp->value=v;
temp->left=NULL;
temp->right=NULL;
}
else if(temp->value>v){
temp->left=insert(temp->left,v);
}
else{
temp->right=insert(temp->right,v);
return temp;
}
};
void preorder(BST *temp){
if(temp!=NULL){
cout<<" -> "<<temp->value;
preorder(temp->left);
preorder(temp->right);
}
}
void inorder(BST *temp){
if(temp!=NULL){
inorder(temp->left);
cout<<" -> "<<temp->value;
inorder(temp->right);
}
}
void postorder(BST *temp){
if(temp!=NULL){
postorder(temp->left);
postorder(temp->right);
cout<<"-> "<<temp->value;
}}
bool search(BST *temp,int v){

if(temp==NULL){
return false;
}
else{
if(temp->value==v){
return true;
}
else if(temp->value>v){
return(search(temp->left,v));
}
else {
return(search(temp->right,v));
}
}
}
13)Given list[10]={2,6,1,3,8,7,9,10,4,5,0};use merge sort to sort the given items
#include<iostream>
using namespace std;
const int size=10;
void merge_sort(int [],int,int);
void merge(int [],int ,int,int);
int main(){
int a[]={9,19,13,8,17,15,11,7,0,3};
cout<<"---------->> Before sorting <<-------------"<<endl<<endl;
for(int i=0;i<size;i++){
cout<<a[i]<<" ";
}
cout<<endl<<endl<<"----------->> After sorting <<-------------"<<endl<<endl;
merge_sort(a,0,9);
for(int i=0;i<size;i++){
cout<<a[i]<<" ";
}
cout<<endl<<endl<<"*******************************************"<<endl<<endl<<e
ndl;
return 0;
}
void merge_sort(int array[],int low,int high){
if(low<high){
int middle=(low+high)/2;
merge_sort(array,low,middle);
merge_sort(array,middle+1,high);
merge(array,low,middle,high);
}
}
void merge(int array[],int low,int middle,int high){
int temp[size];
for(int i=low;i<=high;i++){
temp[i]=array[i];
}
int i=low;
int j=middle+1;
int k=low;
while(i<=middle && j<=high){
if(temp[i]<=temp[j]){
array[k]=temp[i];
i++;
}
else{
array[k]=temp[j];
j++;
}
k++;
}
while(i<=middle){
array[k]=temp[i];
k++;
i++;
}
while(j<=high){
array[k]=temp[j];
k++;
j++;
}
}

14)How do we find the smallest node in the binary search tree?

Answer: Given a non-empty binary search tree (an ordered binary tree), return the
minimum data value found in that tree. Note that it is not necessary to search the entire
tree. A maxValue() function is structurally very similar to this function. This can be solved
with recursion or with a simple while loop.
int minValue(struct node* node) {
What is the runtime complexity to do this in both an unbalanced and balanced binary
search tree, in the worst case?
Answer: O(n) Worst case happens for left skewed trees.
How do we find for the largest node in a binary search tree?
Answer: Similarly we can get the maximum value by recursively traversing the right node
of a binary search tree.
int maxValue(struct node* node) {
What is the runtime complexities for this?
Answer: Similarly O(n) Worst case happens for right skewed trees.
15)In a binary search tree, the successor of some node x is the next largest node after x. For
example, in a binary search tree containing the keys 24,39,41,55,87,92, the successor of 41 is
55. How do we find the successor of a node in a binary search tree?
ANSWER:
If x has two children, its predecessor is the maximum value in its left subtree and its
successor the minimum value in its right subtree.
Tree_Successor(x)
if right[x]!=NIL
then return Tree_Minimum(right[x])
y←p[x]
while (y !=NIL and (x ==right[y])
do x←y
y←p[y]
return y
If I call the sucessor function once, the time complexity is O(h)O(h), which could be
O(n)O(n) or O(logn)O(log⁡n), depending on the kind of tree.
AND
If I call the successor nn times, the time complexity is O(n)O(n) in a balanced tree.

16) What is problem with Binary Search tree?


Answer:
Whenever you build a BST make sure you do not insert the values in increasing or
decreasing order. Or if you find yourself with a degenerate tree it is worthwhile to rebuild it
by removing all its values and re-inserting them in random order.
Height would always be O(log(# nodes)), so search would always be O(logN).
17) Write the algorithm for a merge sort and quick sort. Show result of each step for the
following list {2,6,1,3,8,7,9,10,4,5,0};
ANSWER:
Quick sort:
:Algorithm:
Choose a pivot value (mostly the first element is taken as the pivot value)
2. Position the pivot element and partition the list so that:
· the left part has items less than or equal to the pivot value
· the right part has items greater than or equal to the pivot
value
3. Recursively sort the left part
4. Recursively sort the right part
The following algorithm can be used to position a pivot value and create partition.
Left=0;
Right=n-1; // n is the total number of elements in the list
PivotPos=Left;
while(Left<Right)
{
if(PivotPos==Left)
{
if(Data[Left]>Data[Right])
{
swap(data[Left], Data[Right]);
PivotPos=Right;
Left++;
}
else
Right--;
}
else
{
if(Data[Left]>Data[Right])
{
swap(data[Left], Data[Right]);
PivotPos=Left;
Right--;
}
else
Left++;
}
}
//for detail see data structure and algorithm.pdf page- 80/81.
And video=>c++ Advanced Course-70-Quick Sort-YouTube.MP4

Merge sort:
Algorithm:
1. Divide the array in to two halves.
2. Recursively sort the first n/2 items.
3. Recursively sort the last n/2 items.
4. Merge sorted items (using an auxiliary array).//for detail see a video=>c++ Advanced
Course-69-Merge Sort-YouTube.MP4 and data structure and algorithm.pdf page- 85/86.

18)Given a preorder=[10,2,1,5,3,4,7,6,8,9,12,11,13,14],
Inorder=[1,2,3,4,5,6,7,8,9,10,11,12,13,14] construct a binary search tree and write the post
order traversal of the tree?

SOLUTION:
When we construct a binary search tree, we select the first element in
preorder(Root,Left,Right principle) as the first root.
Then we proceed to the next element in the preorder and check that number in
inorder(Left,Root,Right principle) if it is to the right or the left of the root.
Eg. 10 is root; 2 is the next number to 10 in preorder and it is to the left of 10 in inorder.
Postorder(Left,Right,Root principle): 1,4,6,9,8,7,5,2,11,14,13,12,10

19)Given list{2,6,1,3,8,7,9,10,4,5,0}; create the heap tree and sort the items using heap sort

SOLUTION:
Code:
#include<iostream>
using namespace std;
int main(){
int b[]={4,3,2,6,1,17,10,9,14,19},n=10,i,j,c,p,temp;
for(i=1;i<n;i++){
c=i;
do{
p=(c-1)/2;
if(b[p]<b[c])
{
temp=b[p];
b[p]=b[c];
b[c]=temp;
}
c=p;
}
while(c!=0);
}
for(j=0;j<n;j++){
temp=b[0];
b[0]=b[i];
b[i]=temp;
p=0;
do{
c=2*p+1;
if((b[c]<b[c+1])&&c<j-1)
c++;
if(b[p]<b[c]&&c<j){
temp=b[p];
b[p]=b[c];
b[c]=temp;
}
p=c;
}
while(c<j);
}
cout<<"The sorted list is: ";
for(i=0;i<n;i++){
cout<<" "<<b[i];
}
return 0;
}
//for more details see data structure and algorithm.pdf page- 83/84 and video=>heap
sort-YouTube.MP4
20)Define the following terms Graph terms:
21)Graph:-a diagram displaying data;in particular one showing the relationship b/n two
or more quantities.
a.Directed Graph:-A graph in which the edges are ordered pairs, so that, if the edge
(a,b) is in the graph, the edge (b,a) need not be in the graph and is
distinct from (a,b) if it is.

b.Connected Graph:-A graph whose any two vertices are connected by some path.

c.Complete Graph:-A graph whose all pairs of vertices are adjacent.


d.Cycle:-A closed walk or path with or without repeated vertices allowed.
22)For the following graph give both adjacency matrix and adjacency list
representation. In what order vertices will be visited using Depth First
Search(DFS)? Breadth First Search? Start at A

SOLUTION:

You might also like