Advertisement
yragi_san

Odd Even Linked List

Mar 18th, 2023
901
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode() : val(0), next(nullptr) {}
  7.  *     ListNode(int x) : val(x), next(nullptr) {}
  8.  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  9.  * };
  10.  */
  11.  
  12. struct Linked_List {
  13.   ListNode *head = NULL;
  14.   ListNode *tail = NULL;
  15.   int num_elements = 0;
  16.   void push(int value) {
  17.     ListNode *new_node = new ListNode;
  18.     new_node->val = value;
  19.     new_node->next = NULL;
  20.     if (head == NULL) {
  21.       head = new_node;
  22.       tail = head;
  23.     } else {
  24.       tail->next = new_node;
  25.       tail = tail->next;
  26.     }
  27.     num_elements++;
  28.   }
  29. };
  30.  
  31. class Solution {
  32. public:
  33.     ListNode* oddEvenList(ListNode* head) {
  34.         if(head == NULL)return head;
  35.         Linked_List Odds;
  36.         Linked_List Evens;
  37.         ListNode *current = NULL;
  38.         current = head;
  39.         int i = 0;
  40.         while(current){
  41.             if(i%2==0)Odds.push(current->val);
  42.             else Evens.push(current->val);
  43.             i++;
  44.             current = current->next;
  45.         }
  46.         Odds.tail->next = Evens.head;
  47.         return Odds.head;
  48.     }
  49. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement