i was presented with this function which cuts the first half of a list
and returns the head
but when i compiled it .i get a bug
i cant see the idea in this code
how i cuts by half??
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int value;
struct node *next;
}Node;
Node * what1(Node * source);
int main()
{
Node *p;
p=(Node *)malloc(sizeof(Node));
p->value=1;
p->next=(Node *)malloc(sizeof(Node));
p->next->value=2;
p->next->next=(Node *)malloc(sizeof(Node));
p->next->next->value=3;
p->next->next->next=(Node *)malloc(sizeof(Node));
p->next->next->next->value=4;
what1(p);
free(p);
return 0;
}
Node* what1(Node * source)
{
Node *fast,*slow,*temp;
if (source==NULL||source->next==NULL)
return source;
slow=fast=source;
do
{
temp=slow;
slow=slow->next;
fast=fast->next;
if(fast)
fast=fast->next;
free(temp);
}while(fast);
return slow;
}