Sunday, December 7, 2014

Algorithm for inserting elements from the back of the Linked List to the elements on front of the array interleaving one node each.

Algorithm for printing reversing a array from mid element and inserting nodes between two nodes . 
For example

 -> 11 -> 10 -> 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> null 

should be converted to 

->11 -> 1 -> 10 -> 2 -> 9 -> 3 -> 8 -> 4 -> 7 -> 5 -> 6->null
package midinverse;
class Node {
int data;
Node next;
Node(int val, Node link)
{
data = val;
next = link;
}
}
public class MidInverseJava {
Node headNode;
MidInverseJava()
{
headNode = null;
}
Node addNode(Node toAddNode)
{
if (toAddNode == null)
{
System.out.println("Node to be added is empty");
return null;
}
if(headNode == null)
{
System.out.println("Linked list is empty");
headNode = toAddNode;
return headNode;
}
toAddNode.next = headNode;
headNode = toAddNode;
return headNode;
}
void printNodes(Node firstNode)
{
while(firstNode!=null)
{
System.out.print(" -> "+ firstNode.data);
firstNode = firstNode.next;
}
System.out.println();
}
static int maxCount;
void recursiveInsert(Node tempNode, int count)
{
Node slowPointer = headNode;
if (tempNode == null)
{
maxCount = count;
return;
}
count = count + 1;
recursiveInsert(tempNode.next, count);
for ( int n=0 ; n < (maxCount - count)*2; n++)
{
slowPointer = slowPointer.next;
}
Node xNode = slowPointer.next;
slowPointer.next = tempNode;
tempNode.next = xNode;
if (count==1)
slowPointer.next = null;
}
void midinsert()
{
Node slowPointer, fastPointer;
if(headNode == null || headNode.next == null)
System.out.println("List not length enough !");
for ( slowPointer = headNode, fastPointer=headNode ; fastPointer.next != null ; )
{
slowPointer = slowPointer.next;
fastPointer= fastPointer.next.next;
}
recursiveInsert(slowPointer, 0);
}
public static void main(String [] args)
{
MidInverseJava obj = new MidInverseJava();
Node n1 = new Node(1, null);
Node n2 = new Node(2, n1);
Node n3 = new Node(3, n2);
Node n4 = new Node(4, n3);
Node n5 = new Node(5, n4);
Node n6 = new Node(6, n5);
Node n7 = new Node(7, n6);
Node n8 = new Node(8, n7);
Node n9 = new Node(9, n8);
Node n10 = new Node(10, n9);
Node n11 = new Node(11, n10);
obj.headNode = n11;
obj.printNodes(obj.headNode);
obj.midinsert();
obj.printNodes(obj.headNode);
}
}

No comments:

Post a Comment