c - Splitting Linklist in two parts -


given list, split 2 sublists — 1 front half, , 1 half. if number of elements odd, element should go in front list. frontbacksplit() on list {2, 3, 5, 7, 11} should yield 2 lists {2, 3, 5} , {7, 11}.

code this.

void frontbacksplit(node *head, node **front, node **back) {   if (!head) return;  // handle empty list   node *front_last_node;   node *slow = head;   node *fast = head;   while (fast) {     front_last_node = slow;     slow = slow->next;     fast = (fast->next) ? fast->next->next : null;   }   front_last_node->next = null;  // ends front sublist   *front = head;   *back = slow; } 

problem not getting best run-time , expected output.

generally, code works even-sized lists. consider list of 4 elements -> b -> c -> d -> null , take @ algorithm trace.

a    slow, fast, head b c d null     front_last_node, head b    slow c    fast d null     head b    front_last_node c    slow d null fast 

then erase link b->c , return 2 lists: -> b , c -> d. wanted behavior of function, isn't it?


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -