## Archive for February, 2013

Today we will write a program for appending last N nodes from the beginning to the start of the link list.

Example

input linked is 0->1->2->3->4->5->6->7->8->9 and the value of N is 3 than output must be

7->8->9->0->1->2->3->4->5->6

Code

```        public void AppendLastNNodeToHead(Node<T> root, int n)
{
Node<T> currentNode = root;
Node<T> previousNode = root;

for (int i = 0; i < n; i++)
{
currentNode = currentNode.Next;
if (currentNode == null)
{
Console.WriteLine("List has less number of nodes");
return;
}
}

while (currentNode.Next != null)
{
currentNode = currentNode.Next;
previousNode = previousNode.Next;
}

currentNode.Next = root;
root = previousNode.Next;
previousNode.Next = null;

this.head = root;
}```

Today we will write a program for finding the Kth  element from the last.

Code

```        public void PrintKthElementFromLast(Node<T> head, int k)
{
Node<T> firstPointer = head;
Node<T> secondPointer = head;
int counter = 0;
while (counter < k)
{
if (firstPointer == null)
{
Console.WriteLine("LinkList has less number of nodes");
return;
}
firstPointer = firstPointer.Next;
counter = counter + 1;
}
while (firstPointer != null)
{
secondPointer = secondPointer.Next;
firstPointer = firstPointer.Next;
}
Console.WriteLine(string.Format("{0}th Elements from Last is {1} ", k,                                                             secondPointer.Data));
Console.WriteLine(Environment.NewLine);
}```

Test Case

1->2->3->4->5->6->

2th Elements from Last is 5

1->2->3->4->5->6->20->17->1->7->

3th Elements from Last is 17

1->2->3->4->5->6->20->17->1->7->

4th Elements from Last is 20

1->2->3->4->5->6->20->17->1->7->

10th Elements from Last is 1

Code

```        public static void BingoSort(int[] inputArray)
{
int max = inputArray.Length - 1;
int nextValue = max;

for (int i = max; i >= 0; i--)
{
if (inputArray[i] > nextValue) { nextValue = inputArray[i]; }

}
while ((max > 0) && (inputArray[max] == nextValue))
{
max = max - 1;
}

}```