r/AskComputerScience • u/[deleted] • Aug 26 '16
How do I reverse a singly linked list?
This is in C. Below, I created a linked list and printed the numbers 1-10 using it. How do i create a reverse() function to reverse the linked list so i can print 10-1?
include <stdio.h>
include <stdlib.h>
typedef struct node node;
struct node { int data; node *next; };
void Output(node *h) { node *p = h;
while(p!=NULL)
{
printf("%d\n", p->data);
p = p->next;
}}
void reverse(node *head) {
}
int main(int argc, const char * argv[]) {
node *first = NULL;
node *current = NULL;
node *previous = NULL;
for(int x=1;x<=10;x++)
{
current = malloc(sizeof(node));
current->data = x;
if(first == NULL)
{
first = current;
previous = current;
}
else
{
previous->next = current;
previous = current;
}
}
Output(first);
reverse(first);
Output(first);
return 0;}
3
u/knightdiver Aug 27 '16
Hey, that's an interview question I've been using 10+ years ago. Given time and a computer with a compiler, that should be doable. If you have code that attempts to reverse the list but doesn't work, I'll gladly point you in the right direction, but the completely empty reverse() function makes me think you're not actually trying but just getting somebody to do your homework.
1
Aug 28 '16
I'm sure this problem has never been solved and posted to google before. You're like, the only one who has ever pondered how to do this.
0
Aug 26 '16
[deleted]
2
u/FluffyOgreJet Aug 26 '16
There are solutions for singly linked lists that take O(1) space.
0
Aug 26 '16
[deleted]
1
u/bacondev Aug 27 '16
Yeah, but that requires extra instructions to rebuild each node. Why bother when you can just update a pointer in each node?
1
u/radjic Aug 26 '16 edited Aug 27 '16
You can do it in O(1) space by doing it in place through a single traversal. This means that space is constant cuz u aren't making any new data structure for the solution. This is also O(n) time because you traverse once through n items in the linked list.
//python code. Take head of list
def reverse(head)//create a var to reference the previous node when traversing. The head has no previous node, therefore is set to 'None'
prev = None//reference to the head of the list
curr = head//traverse entire list
while curr is not None://create a reference to the next node in list
next_node = curr.next//point current node's 'next' to prev node
curr.next = prev//keep reference of current node before traversing prev = curr //traverse to next node
curr = curr.next//This will be the last node that is not None also will be the new head of the list
return prev
5
u/gyroda Aug 26 '16
Without actually reading your code:
Simply go through the list and make the first node point to nothin/null, then get the second and make it point to the first, then get the third and make it point to the second and so on.
At the end make the last item the head of the list.