using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SinglyLinkedListExersize
{
/*
* Write a function that would return the 5th element from the
* tail (or end) of a singly linked list of integers, in one pass,
* and then provide a set of test cases against that function
* (please do not use any list manipulation functions that you
* do not implement yourself).
*/
class App
{
public static void main(String[] args) {
int arr[] = new int[] { 0, 1, 2, 3, 4, 5, 6 };
int lastLocation = 0;
while (true) {
try {
System.out.println(arr[lastLocation]);
lastLocation = lastLocation + 5;
} catch (ArrayIndexOutOfBoundsException e) {
//System.out.println("arr Out of index: " + lastLocation);
break;
}
}
lastLocation--;
for (int i = 0; i < 5; i++) {
try {
// This sysout statement ensure that same element is not hit
// twice
System.out.println(arr[lastLocation]);
if(lastLocation < 4) {
System.out.println("Array Length less than 5");
break;
}
// System.out.println("Last element of array: "
// + arr[lastLocation]);
System.out.println("5th Last element of array: "
+ arr[lastLocation - 4]);
break;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(lastLocation--);
}
}
}
}
}
Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.
”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.
Our community of experts have been thoroughly vetted for their expertise and industry experience.