Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //{ Driver Code Starts
- #include<iostream>
- using namespace std;
- /* Link list Node */
- struct Node
- {
- int data;
- struct Node *next;
- Node(int x)
- {
- data = x;
- next = NULL;
- }
- };
- Node* sortedMerge(struct Node* a, struct Node* b);
- /* Function to print Nodes in a given linked list */
- void printList(struct Node *n)
- {
- while (n!=NULL)
- {
- cout << n->data << " ";
- n = n->next;
- }
- cout << endl;
- }
- /* Driver program to test above function*/
- int main()
- {
- int t;
- cin>>t;
- while(t--)
- {
- int n,m;
- cin>>n>>m;
- int data;
- cin>>data;
- struct Node *head1 = new Node(data);
- struct Node *tail1 = head1;
- for (int i = 1; i < n; ++i)
- {
- cin>>data;
- tail1->next = new Node(data);
- tail1 = tail1->next;
- }
- cin>>data;
- struct Node *head2 = new Node(data);
- struct Node *tail2 = head2;
- for(int i=1; i<m; i++)
- {
- cin>>data;
- tail2->next = new Node(data);
- tail2 = tail2->next;
- }
- Node *head = sortedMerge(head1, head2);
- printList(head);
- }
- return 0;
- }
- // } Driver Code Ends
- /* Link list Node
- struct Node {
- int data;
- struct Node *next;
- Node(int x) {
- data = x;
- next = NULL;
- }
- };
- */
- //Function to merge two sorted linked list.
- Node* reverseList(Node* head)
- {
- if (head->next == NULL)
- return head;
- Node* rest = reverseList(head->next);
- head->next->next = head;
- head->next = NULL;
- return rest;
- }
- // Given two non-empty linked lists 'a' and 'b'
- Node* sortedMerge(Node* a, Node* b)
- {
- // Reverse Linked List 'a'
- a = reverseList(a);
- // Reverse Linked List 'b'
- b = reverseList(b);
- // Initialize head of resultant list
- Node* head = NULL;
- Node* temp;
- // Traverse both lists while both of them
- // have nodes.
- while (a != NULL && b != NULL) {
- // If a's current value is greater than or equal to
- // b's current value.
- if (a->data >= b->data) {
- // Store next of current Node in first list
- temp = a->next;
- // Add 'a' at the front of resultant list
- a->next = head;
- // Make 'a' - head of the result list
- head = a;
- // Move ahead in first list
- a = temp;
- }
- // If b's value is greater. Below steps are similar
- // to above (Only 'a' is replaced with 'b')
- else {
- temp = b->next;
- b->next = head;
- head = b;
- b = temp;
- }
- }
- // If second list reached end, but first list has
- // nodes. Add remaining nodes of first list at the
- // beginning of result list
- while (a != NULL) {
- temp = a->next;
- a->next = head;
- head = a;
- a = temp;
- }
- // If first list reached end, but second list has
- // nodes. Add remaining nodes of second list at the
- // beginning of result list
- while (b != NULL) {
- temp = b->next;
- b->next = head;
- head = b;
- b = temp;
- }
- // Return the head of the result list
- return head;
- }
- // https://practice.geeksforgeeks.org/problems/merge-two-sorted-linked-lists/
Advertisement
Add Comment
Please, Sign In to add comment