Expedia Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
#include <iostream>
#include <stdlib.h>
#include "List.h"
#include "Node.h"
using namespace std;
int main()
{
int k = 0;
int input = 0;
int element = 0;
int listSize = rand() % 80;
List myList;
cout << endl;
for(int i = 0; i < listSize; i++){
input = rand() % 80;
myList.addNode(input);
}
cout << "To find the kth last element in the list, type the value of k: ";
cin >> k;
Node *ptr1 = myList.head;
int counter = 1;
while(counter != k){
ptr1 = ptr1->getNext();
counter++;
}
Node *ptr2 = myList.head;
while(ptr1->getNext() != NULL){
ptr1 = ptr1->getNext();
ptr2 = ptr2->getNext();
}
element = ptr2->getData();
cout << "The " << k << "th last element in the list: ";
myList.printList();
cout << "is " << element;
}
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
// Time Complexity O(n)
Node getElement(Node head, int n) {
Node first = head, second = head;
int count = 0;
while(null != first && count < n) {
first = first.next;
count++;
}
if(count != n) {
return first;
}
while(null != first) {
first = first.next;
second = second.next;
}
return second;
}
Take two pointers initialise second pointer after moving first pointer n positions so when first pointer will be at last position second pointer will be at nth last position
- Anonymous March 03, 2013