When starting, always break the problem you are trying to solve into smaller problems and solve those. If you split it enough, the problems you really have to solve are practically one liners that can easily be verified as correct.
What do you need? First off a method that extracts the last digit of an integer. Ok, thats easy, the last digit of any number is the remainder of dividing by 10:
private static int ExtractLastDigit(this int i)
{
return i % 10;
}
We also need a method that extracts the first digit. The easiest way to do this is to scale down the number so that the digit we are looking for is the only digit left. We can do this using Log10:
private static int ExtractFirstDigit(this int i)
{
var scale = (int)Math.Log10(i);
return (int)(i / Math.Pow(10, scale));
}
Now, there are tons of ways you can do this. The easiest to understand is to build two collections; one with all the first digits and another with the all the last digits an check if all the items in the former are present in the latter. Because you will be searching assiduously inside the latter, if the input collection is large enough, storing the last digits in a search efficient collection is, generally, a good idea. The framework provides such collection: HashSet<T>.
I will be using linq, but building the collections with classical loops is rather trivial.
var firstItems = inputStack.Select(i => i.ExtractFirstDigit());
var lastItems = new HashSet<int>(inputStack.Select(i => i.ExtractLastDigit()))
And now, with the logic operator All linq provides:
var validInput = firstItems.All(f => lastItems.Contains(f));
Which roughly translates to:
var validInput = true;
foreach (var first in firstItems)
{
if (!lastItems.Contains(f))
{
validInput = false;
break;
}
}
And you are done.
Are there more efficient solutions? Sure, but do you really need them? If the answer is yes, get used to first building a working solution and then start trying to optimize it with clear performance goals you can measure and test. If you don't or it already meets your goals, then you have a working solution easy to understand and mantain.