Saturday, 19 April 2014

LinkList:Folding a LinkList

Input : LinkList(Even Number of  Nodes)

Output : Folded Link List





Input : LinkList(Odd Number of  Nodes)



Output : Folded Link List



Solution:

We begin with a recursive algorithm to solve the problem. The function FoldLinkList will take input as head of list and return the head after connect First node( 1 ) to LastNode ( 6 ) and again the FoldLinkList is called on Nodes 2 .Function LastNode will return the last Element of current linklist and set the previous node of last node to null;


Code:
Class to represent Node in a LinkList





2 comments:

  1. HI Ashish,
    the complexity of code is O(n^2).
    refer to the post:
    http://codingrecipies.blogspot.in/2014/04/fold-linked-list.html?showComment=1397981741858#c7157818208249283696

    ReplyDelete