class Solution: def alternatingSplitList(self, head): ll = [None, None] last1 = last2 = None count = 0 while head: NEXT = head.next head.next = None if count%2 == 0: if last1: last1.next = head else: ll[0] = head last1 = head else: if last2: last2.next = head else: ll[1] = head last2 = head head = NEXT count += 1 return ll
Table of Contents
0:00 Problem Statement
0:53 Solution
3:55 Pseudo Code
6:09 Code - Python
6:57 Code - C++
class Solution:
def alternatingSplitList(self, head):
ll = [None, None]
last1 = last2 = None
count = 0
while head:
NEXT = head.next
head.next = None
if count%2 == 0:
if last1:
last1.next = head
else:
ll[0] = head
last1 = head
else:
if last2:
last2.next = head
else:
ll[1] = head
last2 = head
head = NEXT
count += 1
return ll
class Solution {
public:
// Function to split a linked list into two lists alternately
vector alternatingSplitList(struct Node* head) {
vector ll(2, NULL);
Node *last1 = NULL, *last2 = NULL;
int count = 0;
while (head) {
Node *next = head->next;
head->next = NULL;
if (count%2 == 0) {
if (last1)
last1->next = head;
else
ll[0] = head;
last1 = head;
}
else {
if (last2)
last2->next = head;
else
ll[1] = head;
last2 = head;
}
head = next;
count++;
}
return ll;
}
};