Advertisement
193030

Linked list reverse k to n WIP working

Nov 13th, 2021
1,159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. // LL_.cpp : This file contains the 'main' function. Program execution begins and ends there.
  2. //
  3. #include <iostream>
  4.  
  5. struct Node
  6. {
  7.     int data;
  8.     struct Node* next;
  9. };
  10.  
  11. using namespace std;
  12.  
  13. void add(int data, struct Node ** head)
  14. {
  15.     struct Node* p = new Node;
  16.     p->data = data;
  17.     p->next = *head;
  18.     *head = p;
  19.    
  20. }
  21.  
  22. void display(struct Node** head)
  23. {
  24.     struct Node* p = *head;
  25.     while(p)
  26.     {
  27.         cout << p->data << " ";
  28.         p = p->next;
  29.     }
  30.     cout << endl;
  31. }
  32.  
  33. void reverse(struct Node**head)
  34. {
  35.    
  36.     struct Node* prev = NULL;
  37.     struct Node* current = *head;
  38.     struct Node* next = NULL;
  39.     while (current != NULL) {
  40.         next = current->next;
  41.         current->next = prev;
  42.         prev = current;
  43.         current = next;
  44.     }
  45.     *head = prev;
  46. }
  47.  
  48. void reverse2(struct Node** head)
  49. {
  50.     struct Node* lastHead;
  51.     int k = 2;
  52.     k--; // fix
  53.     int n = 4;
  54.     lastHead = *head;
  55.     while (k--)
  56.         lastHead = lastHead->next;
  57.     cout << lastHead->data << endl;
  58.  
  59.     struct Node* prev = NULL;
  60.     struct Node* current = lastHead->next;
  61.     struct Node * lastTemp = lastHead->next;
  62.     struct Node* next = NULL;
  63.     while (current != NULL && n--) {
  64.         next = current->next;
  65.         current->next = prev;
  66.         prev = current;
  67.         current = next;
  68.     }
  69.     lastHead->next = prev;
  70.     struct Node* p = *head;
  71.     while (p->next)
  72.         p = p->next;
  73.     p->next = next;
  74.  
  75.  
  76. }
  77.  
  78.  
  79. int main()
  80. {
  81.     struct Node* first = NULL;
  82.     add(8, &first);
  83.     add(9, &first);
  84.     add(10, &first);
  85.     add(20, &first);
  86.     add(30, &first);
  87.     add(40, &first);
  88.     add(50, &first);
  89.     add(60, &first);
  90.     display(&first);
  91.     reverse2(&first);
  92.     display(&first);
  93. }
  94.  
  95. // working
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement