Question

In: Computer Science

Question: Rotate and sort the list:-   In this problem, you have to first implement a singly...

Question:

Rotate and sort the list:-  

In this problem, you have to first implement a singly linked list whose each node should have the following attributes,

● key - a positive integer

● next - address/pointer/reference to the next node in the linked list You will receive Q1 queries of following types,

● 1 x - Append a node to the linked list whose key should be x. After appending, print, in a new line, the key of each node in the linked list separated by a single space.

● 2 x - Delete the node in the linked list whose key is x.If such a node is not present in the linked list, no changes should be made. After this, print, in a new line, the key of each node in the linked list separated by a single space. The deleted node, if any, should be added in another linked list. Then you will receive Q2 queries of the following type,

● k - The linked list should be rotated towards right by |k| steps if k > 0, otherwise the linked list should be rotated towards left by |k| steps. k will always be an integer. Once all of the above Q2 queries are done, print, in a new line, the key of each node in the linked list separated by a single space. Then you have to merge the two linked lists together after sorting (by key), each of them using the merge sort algorithm. Once done, print in a new line, the key of each node in the linked list separated by a single space. Note that the linked list in the end should also be sorted by key.

Input Format - The first line will contain a positive integer, Q1 , following which there will be Q1 lines containing queries as described above. Then the very next line will contain a positive integer Q2 following which will be Q2 lines containing queries as described above.

Output Format - Q1 + 2 lines with space separated values of the key of each node in the linked list as explained above.

Constraints ● 0 < Q1 < 1000

● 0 < Q2 < 10000

● 0 < key, x < 1000

● -100 < k < 100

Solutions

Expert Solution

#include <iostream>
using namespace std;
//defining node of a linked list
class Node  
{  
    public: 
    int data;  
    Node *next;  
};
//appending node to the end of linked list
void append(Node** head_ref, int new_data)   
{   
    Node* new_node = new Node();  
    Node *last = *head_ref;  
    new_node->data = new_data;   
    new_node->next = NULL;   
    if (*head_ref == NULL)   
    {   
        *head_ref = new_node;   
        return;   
    }    
    while (last->next != NULL)   
        last = last->next;   
    last->next = new_node;   
    return;   
}   
//deleting node of the linked list
void deleteNode(struct Node **head_ref, int key) 
{ 
   if (*head_ref == NULL) 
      return; 
   Node* temp = *head_ref; 
   if (temp->data==key) 
    { 
        *head_ref = temp->next;   // Change head 
        free(temp);               // free old head 
        return; 
    } 
  
    // Find previous node of the node to be deleted 
    for (int i=0; temp!=NULL && temp->data!=key; i++) 
         temp = temp->next; 
  
    // If position is more than number of nodes 
    if (temp == NULL || temp->next == NULL) 
         return; 
    Node *next = temp->next->next; 
    free(temp->next);  // Free memory 
    temp->next = next;  // Unlink the deleted node from list 
}
//rotating a linked list if k is negative(i.e counter clockwise)
void rotate_left(Node** head_ref, int k)
{
    if (k == 0)
        return;
    Node* current = *head_ref;
    int count = 1;
    while (count < k && current != NULL) {
        current = current->next;
        count++;
    }
    if (current == NULL)
        return;
    Node* kthNode = current;
    while (current->next != NULL)
        current = current->next;
    current->next = *head_ref;
    *head_ref = kthNode->next;
    kthNode->next = NULL;
} 
//function to rotate linked list towards right clockwise by k
Node* rotate_right(Node* head, int k) 
{ 
    if (!head) 
        return head; 
    Node* tmp = head; 
    int len = 1; 
    while (tmp->next != NULL) { 
        tmp = tmp->next; 
        len++; 
    } 
    if (k > len) 
        k = k % len; 
    k = len - k; 
    if (k == 0 || k == len) 
        return head; 
    Node* current = head; 
    int cnt = 1; 
    while (cnt < k && current != NULL) { 
        current = current->next; 
        cnt++; 
    } 
    if (current == NULL) 
        return head; 
    Node* kthnode = current; 
    tmp->next = head; 
    head = kthnode->next; 
    kthnode->next = NULL; 
    // Return the updated head pointer 
    return head; 
} 
//function which return size of the node
int linked_list_size(Node *head)
{
    Node *temp = head;
    int count = 0;
    while(temp!=NULL)
    {
       temp = temp->next;
       count++;
    }
    return count;
}
//function to print the node
void printList(Node* head)
{
    while (head != NULL) {
        cout << head->data << " ";
        head = head->next;
    }
}
int main() {
    int q1,q2;
    cin>>q1;
    Node* head = NULL;
    for(int i=0;i<q1;i++)
    {
        int sub_query_no,key;
        cin>>sub_query_no>>key;
        if(sub_query_no==1)
        {
            append(&head,key);
        }
        else
        {
            deleteNode(&head,key);
        }
        printList(head);
        cout<<endl;
    }
    int size = linked_list_size(head);
    cin>>q2;
    for(int i=0;i<q2;i++)
    {
        int k;
        cin>>k;
        if(k>=0)
        { 
           k = k%size;
           head =  rotate_right(head,k);
           printList(head);
           cout<<endl;
        }
        else
        {
            k = -1*k;
            k = k%size;
            rotate_left(&head,k);
            printList(head);
            cout<<endl;
        }
    }
}

INPUT AND OUTPUT


Related Solutions

In C++, Implement the queue ADT with a singly linked list
In C++, Implement the queue ADT with a singly linked list
Data Structure and Algorithm: 1. You are asked to use insertion sort to sort a singly...
Data Structure and Algorithm: 1. You are asked to use insertion sort to sort a singly linked list in ascending order. Why is this a bad idea? How does insertion sort’s runtime complexity change if you were to use it to sort a linked list? 2. Your classmate thinks that input arrays to the merge operation of merge sort don’t need to be in sorted order. Is your classmate right or wrong? Why?
4) Implement the Selection Sort algorithm discussed in class to sort a list of a certain...
4) Implement the Selection Sort algorithm discussed in class to sort a list of a certain size. The list is to be implemented using a dynamic array as well as a singly linked list. You are required to compare the performance (sorting time) for the dynamic array and singly-linked list-based implementations. You are given the startup codes for the dynamic array and singly-linked list based implementations. You are required to implement the Selection Sort function in each of these codes....
Problem 2 For the same list as above, sort the list in such a way where...
Problem 2 For the same list as above, sort the list in such a way where the first set of numbers are ascending even and the second set of numbers are ascending odd. Your output should look like the following: [ 2, 4, 6, … 1, 3, 5 .. ]. The list is A = [ 6, 9, 0, 4, 2, 8, 0, 0, 8, 5, 2, 1, 3, 20, -1 ]
Problem Description: Using Python write a Singly‐Linked List (with only the Head pointer) that supports the...
Problem Description: Using Python write a Singly‐Linked List (with only the Head pointer) that supports the following operations: 1. Adding an element at the middle of the list. 2. Removing the middle element of the list (and return the data). 3. Adding an element at a given index. 4. Removing an element at a given index (and return the data). For #1 and #2, ignore the operations if the length of the list is an even number. For #3, if...
In this lab, you will implement Heap Sort algorithm in C++ and Report the number of...
In this lab, you will implement Heap Sort algorithm in C++ and Report the number of steps and the CPU running time in a table, please show the code and output Approximation the constant c in the complexity of heap sort (cnlgn) by inspecting the results For each algorithm, and for each n = 100, 200, 300, 400, 500, 1000, 4000, 10000, measure its running time and number of steps when the input is (1) already sort, i.e. n, n-1,...
(Write a C# program DO NOT USE CLASS)Implement the merge sort algorithm using a linked list...
(Write a C# program DO NOT USE CLASS)Implement the merge sort algorithm using a linked list instead of arrays. You can use any kind of a linked structure, such as single, double, circular lists, stacks and/or queues. You can populate your list from an explicitly defined array in your program. HINT: You will not be using low, middle and high anymore. For finding the middle point, traverse through the linked list while keeping count of the number of nodes. Break...
(50’) Implement Quick-Sort algorithm in quickSort.cpp, where you are expected to implement three functions, swap(), partition()...
(50’) Implement Quick-Sort algorithm in quickSort.cpp, where you are expected to implement three functions, swap(), partition() and quickSort(). You are expected to call swap() within partition(), to call partition() within quickSort(), and you are not expected to declare/ implement other additional functions nor change the main() function. OPTIONAL: If you don’t need/ want to use swap() in your implementation, that is fine. Just delete/ comment it. quickSort.cpp #include <iostream> using namespace std;    // A helper function to facilitate swapping...
by java Implement a linked list generic queue. Remember queues are first in first out (FIFO)....
by java Implement a linked list generic queue. Remember queues are first in first out (FIFO). Use the driver to then test each of the methods. Simply download it and place it with the other source files. Create a class GenLLQueue which has the following: Internal class ListNode which contains: Instance variable data of type T Instance variable link of type ListNode Default constructor that sets both instance variables to null Instance Variables head which is of type ListNode which...
You are provided with an array of Strings and a list of Strings. Sort the elements...
You are provided with an array of Strings and a list of Strings. Sort the elements (1) in natural order, (2) in reverse natural order and (3) by the length of each String. You can fill in the details by using the following stub file: import java.util.Arrays; import java.util.Collections; import java.util.List; public class Midterm01 { public static void main(String[] args) { String[] arrayOfCities = { "Atlanta", "Savannah", "New York", "Dallas", "Rio" }; List<String> listOfCities = Arrays.asList("Atlanta", "Savannah", "New York", "Dallas",...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT