Goldman Sachs Interview Question
Software Engineer / DevelopersHere is the program in C#
using System;
using System.Collections.Generic;
using System.Text;
namespace Get5thnode
{
public class Get5thnode
{
static void Main()
{
LinkedList<string> myll = new LinkedList<string>();
LinkedListNode<string> node1 = new LinkedListNode<string>("1");
myll.AddFirst(node1);
LinkedListNode<string> node2 = new LinkedListNode<string>("2");
myll.AddAfter(node1, node2);
LinkedListNode<string> node3 = new LinkedListNode<string>("3");
myll.AddAfter(node2, node3);
LinkedListNode<string> node4 = new LinkedListNode<string>("4");
myll.AddAfter(node3, node4);
LinkedListNode<string> node5 = new LinkedListNode<string>("5");
myll.AddAfter(node4, node5);
LinkedListNode<string> node6 = new LinkedListNode<string>("6");
myll.AddAfter(node5, node6);
LinkedListNode<string> node7 = new LinkedListNode<string>("7");
myll.AddAfter(node6, node7);
LinkedListNode<string> node8 = new LinkedListNode<string>(null);
myll.AddAfter(node7, node8);
int target = myll.Count - 5;
LinkedListNode<string> head = myll.First;
LinkedListNode<string> current = head;
while (!(current == null))
{
for (int count = 0; count < myll.Count; count++)
{
if (count == target)
{
Console.WriteLine(current.Value);
}
if (!(current.Next == null))
current = current.Next;
}
}
Console.Read();
}
}
}
{
List *last=head;
// find the fifth element from the head element of list
for(int i=0; i<5; ++i) {
if( !last->next )
return null;
last=last->next;
}
// step through the list until last element riches the end
// at the same time advance head with every loop
while(last=last->next) head=head->next;
// head will still be 5 elements behind the last node.
return head;
}
take 2 pointer
- king_d July 14, 20081.both point starting node
2. move 2nd pointer to 5 nodes now it points 5th node
3. move both 1-step till 2nd reaches end (2nd->next == NULL)
4. when 2nd reaches 1st pointer will be at 5th node from tail.