From my original question on Stack Overflow: Is my implementation of reversing a linked list correct?
I'm a beginner at C and I'd like to know about style, and correctness of the reverse algorithms. What about memory management?
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int val;
struct Node *next;
} Node;
Node * build_list(int num);
Node * reverse_list(Node * head);
static Node * r_reverseItem(Node * last, Node * head);
Node * r_reverse(Node * head);
/*
* Function which iterates to 100 creating nodes
* and linking them to head
*
*/
Node * build_list(int num) {
Node * head = NULL;
Node * curr;
int i;
for(i=0;i<num;i++) {
curr = (Node *)malloc(sizeof(Node));
curr->val = i;
curr->next = head;
head = curr;
}
return head;
}
/*
* Function which reverses linked list
* by traversing list and flipping ptr of curr to last
* @param head
*
*/
Node * reverse_list(Node * head) {
if (head == NULL) //only one elem
return NULL;
Node * last = NULL;
do {
Node * next = head->next;
head->next = last;
last = head;
head = next;
}
while (head != NULL);
return last;
}
/*
* Function which recursively reverses linked list
* @param last
* @param head
*
*/
static Node * r_reverseItem(Node * last, Node * head) {
if (head == NULL)
return last;
Node * next = head->next;
head->next = last;
return r_reverseItem(head,next);
}
Node * r_reverse(Node * head) {
return r_reverseItem(NULL, head);
}
int main (void) {
Node * head = build_list(5);
Node * curr;
head = r_reverse(head);
// head = reverse_list(head);
while(head) {
printf("%d\n",head->val);
curr = head;
head = head->next;
free(curr);
}
return 0;
}