Given a singly linked list, find middle of the linked list and set middle node of the linked list at beginning of the linked list.
Examples:
Input : 1 2 3 4 5
Output : 3 1 2 4 5
Input : 1 2 3 4 5 6
Output : 4 1 2 3 5 6
The idea is to first find middle of a linked list using two pointers, first one moves one at a time and second one moves two at a time. When second pointer reaches end, first reaches middle. We also keep track of previous of first pointer so that we can remove middle node from its current position and can make it head.
/* Link list node */
struct
Node {
int
data;
struct
Node* next;
};
Node* function(Node* head){
if(!head || !head->next) return head;
Node* fast=head;
Node* slow=head;
Node* pre=NULL;
while(fast&&fast->next){
pre=slow;
slow-next;
fast-next-next;
}
pre-next=slow-next;
slow-next=head;
head=slow;
retuen head;
}
No comments:
Post a Comment