Skip to content

Instantly share code, notes, and snippets.

@jakubtuchol
Last active October 5, 2016 19:18
Show Gist options
  • Select an option

  • Save jakubtuchol/98375b4660abd96072f49738bdc74cfc to your computer and use it in GitHub Desktop.

Select an option

Save jakubtuchol/98375b4660abd96072f49738bdc74cfc to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct node {
struct node *next;
int val;
};
struct node *reverse_list(struct node *ll)
{
struct node *head = NULL;
struct node *next = NULL;
struct node *prev = ll;
while (prev != NULL)
{
head = prev;
prev = prev->next;
head->next = next;
next = head;
}
return head;
}
int main() {
struct node *fake_head = (struct node *) malloc(sizeof(struct node));
int i;
struct node *head = fake_head;
for (i = 0; i < 10; i++)
{
head->next = (struct node *) malloc(sizeof(struct node));
head = head->next;
head->val = i;
}
head = fake_head->next;
head = reverse_list(head);
struct node *prev;
for (i = 9; i >= 0; i--)
{
assert(head->val == i);
prev = head;
head = head->next;
free(prev);
}
free(fake_head);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment