Skip to content

Instantly share code, notes, and snippets.

@TheRayTracer
Last active October 6, 2015 20:48
Show Gist options
  • Select an option

  • Save TheRayTracer/3051091 to your computer and use it in GitHub Desktop.

Select an option

Save TheRayTracer/3051091 to your computer and use it in GitHub Desktop.
Example code to find the nth node from the end of a linked list using only one pass.
#include <iostream>
#include <assert.h>
namespace std { };
using namespace std;
struct node
{
node* next;
size_t data;
};
const node* find_nth_node_from_tail(const node* n, size_t i)
{
const node* t = n;
while (n != NULL)
{
n = n->next;
if (i == 0)
{
t = t->next;
}
else
{
--i;
}
}
return t;
}
const node* find_nth_node_from_tail_improved(const node* n, size_t i)
{
const node* t = n;
while (i-- > 0 && n != NULL)
{
n = n->next;
}
while (n != NULL)
{
n = n->next;
t = t->next;
}
return t;
}
node* reverse_linked_list(node* head)
{
if (head != NULL)
{
node* prev = NULL, * current = NULL, * next = NULL;
current = head;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
}
return head;
}
int main(int argc, char* argv[])
{
node list[8];
list[0].data = 1;
list[0].next = &list[1];
list[1].data = 2;
list[1].next = &list[2];
list[2].data = 3;
list[2].next = &list[3];
list[3].data = 4;
list[3].next = &list[4];
list[4].data = 5;
list[4].next = &list[5];
list[5].data = 6;
list[5].next = &list[6];
list[6].data = 7;
list[6].next = &list[7];
list[7].data = 8;
list[7].next = NULL;
const node* result = find_nth_node_from_tail_improved(list, 5);
assert(result->data == 4);
result = reverse_linked_list(list);
assert(result->data == 8);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment