Advertisement
rishu110067

Untitled

Jan 23rd, 2022
837
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.97 KB | None | 0 0
  1. /*
  2.  * Complete the function below.
  3.  */
  4. /*
  5. For your reference:
  6. LinkedListNode {
  7.     int val;
  8.     LinkedListNode *next;
  9. };
  10. */
  11. LinkedListNode* reverseList(LinkedListNode* head)
  12. {
  13.     LinkedListNode* prev = NULL;
  14.     LinkedListNode* succ = NULL;
  15.    
  16.     LinkedListNode* curr = head;
  17.    
  18.     while(curr != NULL)
  19.     {
  20.         succ = curr->next;
  21.         curr->next = prev;
  22.         prev  = curr;
  23.         curr = succ;
  24.     }
  25.     return prev; //prev will contain the head of reversed List
  26. }
  27.  
  28. LinkedListNode* mergeLists(LinkedListNode* l1, LinkedListNode* l2)
  29. {
  30.     LinkedListNode* sentinel = (LinkedListNode*)malloc(sizeof(LinkedListNode));
  31.    
  32.     sentinel->next = NULL;
  33.    
  34.     LinkedListNode* curr = sentinel;
  35.    
  36.     while(l1 != NULL && l2 != NULL)
  37.     {
  38.         curr->next = l1;
  39.         curr = l1;
  40.         l1 = l1->next;
  41.        
  42.         curr->next = l2;
  43.         curr =l2;
  44.         l2 = l2->next;
  45.      
  46.     }
  47.    
  48.     // if Odd list, then l1 wouldn't be null and we need to add extra element at end
  49.     if(l1 != NULL)
  50.     {
  51.         curr->next = l1;
  52.     }
  53.  
  54.     return sentinel->next;
  55.    
  56. }
  57.  
  58. LinkedListNode* zip_given_linked_list(LinkedListNode* head) {
  59.    
  60.    
  61.     if(head == NULL)
  62.     {
  63.         return NULL;
  64.     }
  65.        
  66.    
  67.     // Find the middle of List and split into 2 lists
  68.     // reverse the 2nd list
  69.     // Merge both the list
  70.     // if Odd list, then add extra element at end
  71.    
  72.     //T(n) = O(n)
  73.     // Aux space = O(1)
  74.  
  75.     LinkedListNode* slow = head;
  76.     LinkedListNode* fast = head;
  77.    
  78.     LinkedListNode* head1 = NULL;
  79.    
  80.     while(fast->next != NULL && fast->next->next != NULL)
  81.     {
  82.         slow = slow->next;
  83.         fast = fast->next->next;
  84.     }
  85.    
  86.     // Slow pointer at middle
  87.     head1 = slow->next;
  88.     slow->next = NULL;
  89.    
  90.     // Reverse second List
  91.     head1 = reverseList(head1);
  92.    
  93.     // Merge the two lists
  94.     head = mergeLists(head, head1);
  95.    
  96.     return head;
  97.    
  98. }
  99.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement