Untitled
unknown
plain_text
2 years ago
1.2 kB
15
Indexable
struct Node
{
int data;
struct Node *next;
};
// Function to create new node in a linkedlist
Node* newNode(int key)
{
Node *temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
void reverse_list(Node **head)
{
Node *prev = NULL;
Node *curr = *head;
Node *next;
while (curr && curr->next)
{
next = curr->next;
curr->next = prev;
curr = next;
prev = curr;
}
}
// Main function to reorder a linked list
void reorder_list(Node **head)
{
Node *slow = *head, *fast = slow->next;
while (fast->next && fast->next->next)
{
slow = slow->next;
fast = fast->next;
}
Node *head1 = *head;
Node *head2 = slow;
slow->next = NULL;
reverse_list(&head2);
*head = newNode(0); // Assign dummy Node
Node *curr = *head;
while (head1 && head2)
{
if(head1) {
curr->next = head1;
curr = curr->next;
head1 = head1->next;
if(head2) {
curr->next = head2;
curr = curr->next;
head2 = head2->next;
}
}
}
}Editor is loading...
Leave a Comment