Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created January 30, 2015 22:39
Show Gist options
  • Save dgodfrey206/13a7d4d499db6a31ec78 to your computer and use it in GitHub Desktop.
Save dgodfrey206/13a7d4d499db6a31ec78 to your computer and use it in GitHub Desktop.
Nth from end for singly linked list
/* nth node from end */
void nthNodeFromEnd(node* head, int n)
{
int size = 0;
node* temp = head;
for (; temp; ++size, temp = temp->next)
{ }
if (size < n)
return;
temp = head;
for (int i = 0; i < size - n - 1; ++i, temp = temp->next)
{ }
if (temp)
std::cout << n << "th node from end is " << temp->data << '\n';
}
/* nth node from end #2 (instructions taken from site) */
void nthNodeFromEndOther(node* head, int n)
{
node* ref = head;
node* main = head;
for (int i = 0; i <= n; ++i)
ref = ref->next;
while (ref)
{
ref = ref->next;
main = main->next;
}
if (main)
std::cout << n << "th node from end is " << main->data << '\n';
else
std::cout << "Could not find element at position.\n";
}
/* Delete linked list */
void deleteLinkedList(node*& head)
{
while (head)
{
node* temp = head->next;
head = temp;
delete head;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment