1.Odd-Even Linked List
Given a singly linked list, group all odd nodes together followed by the even nodes. Here the odd-even refers to node number and not the value in the nodes.
// Example input output
Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULLSolution I : (Using two traversal and new list)
class Solution
{
public:
ListNode *oddEvenList(ListNode *head)
{
ListNode *head1 = NULL;
if (head == NULL)
{
return head;
}
ListNode *p = head;
int i = 1;
while (p != NULL)
{
if (i % 2 != 0)
{
ListNode *temp = new ListNode;
temp->val = p->val;
temp->next = NULL;
if (head1 == NULL)
{
head1 = temp;
}
else
{
ListNode *q = head1;
while (q->next != NULL)
{
q = q->next;
}
q->next = temp;
}
}
p = p->next;
i++;
}
i = 1;
p = head;
while (p != NULL)
{
if (i % 2 == 0)
{
ListNode *temp = new ListNode;
temp->val = p->val;
temp->next = NULL;
if (head1 == NULL)
{
head1 = temp;
}
else
{
ListNode *q = head1;
while (q->next != NULL)
{
q = q->next;
}
q->next = temp;
}
}
p = p->next;
i++;
}
return head1;
}
};Solution II : (Using 2 pointer)
Last updated