Midterm DSA INT2210 5
Midterm DSA INT2210 5
• Submission format:
1
1. Given a doubly linked list, the task is to sort the doubly linked list in non-decreasing
order using merge sort.
Examples:
Input: 10 ↔ 8 ↔ 4 ↔ 2
Output: 2 ↔ 4 ↔ 8 ↔ 10
Input: 5 ↔ 3 ↔ 2
Output: 2 ↔ 3 ↔ 5
// C ++ program for merge sort on doubly linked list
class Node {
public :
int data ;
Node * next ;
Node * prev ;
Node ( int x) {
data = x;
next = NULL ;
prev = NULL ;
}
};
int main () {
2
head - > next - > next - > prev = head - > next ;
head - > next - > next - > next = new Node (2) ;
head - > next - > next - > next - > prev = head - > next - > next ;
printList ( head ) ;
return 0;
}
int main () {
string exp = " a + b *( c ^d - e ) ^( f + g * h ) -i " ;
infixToPostfix ( exp ) ;
return 0;
}
3
Node ( int k ) {
key = k ;
left = nullptr ;
right = nullptr ;
height = 1;
}
};
// Driver Code
int main () {
Node * root = nullptr ;
4
preOrder ( root ) ;
return 0;
}
// Driver ’s code
int main () {
vector < int > arr = { 9 , 4 , 3 , 8 , 10 , 2 , 5 };
// Function call
heapSort ( arr ) ;
5. Vasya has found a strange device. On the front panel of a device there are: a red
button, a blue button and a display showing some positive integer. After clicking the red
button, device multiplies the displayed number by two. After clicking the blue button,
device subtracts one from the number on the display. If at some point the number stops
being positive, the device breaks down. The display can show arbitrarily large numbers.
Initially, the display shows number n. Bob wants to get number m on the display. What
minimum number of clicks he has to make in order to achieve this result?
Input: The first and the only line of the input contains two distinct integers n and m
(1 ≤ n, m ≤ 104 ), separated by a space.
Output: Print a single number — the minimum number of times one needs to push the
button required to get the number m out of number n.
5
Examples:
Input: 4 6
Output: 2
Input: 10 1
Output: 9
// C ++ program to find minimum number of clicks
# include < bits / stdc ++. h >
using namespace std ;
// Driver ’s code
int main () {
int n = 4 , m = 6;
cout << " Minimum clicks to transform " << n << " to " << m <<
" : " << minClicks (n , m ) << endl ;
return 0;
}
6
// A utility function to print the grouped anagrams
void pri nt An ag ra mG ro up s ( vector < vector < string > >& groups ) {
cout << groups . size () << endl ;
// Driver ’s code
int main () {
vector < string > strs = { " eat " , " tea " , " tan " , " ate " , " nat " , "
bat " };
// Function call
vector < vector < string > > anagramGroups = groupAnagrams ( strs ) ;
// Output
cout << " Grouped anagrams : " << endl ;
pr in tA na gr am Gr ou ps ( anagramGroups ) ;
return 0;
}