Sunday, December 14, 2008

reversing a linked list

#include "stdio.h"
#include "stdlib.h"

#define MAX 10 /* max of 10 elements */

struct lnode
{
int number;
struct lnode *next;
};

/* add a lnode at the beginning of the list */
void llist_add_begin(struct lnode **n, int val);
/* reverse the whole list */
void llist_reverse(struct lnode **n);
/* display the whole linked list */
void llist_display(struct lnode *n);

int main(void)
{
struct lnode *new = NULL;
int i = 0;

/* insert some numbers */
for(i = 0; i <= MAX; i++)
llist_add_begin(&new, i);

printf("linked list before reversal:");
llist_display(new);
llist_reverse(&new);
printf("linked list after reversal:");
llist_display(new);

return 0;
}

/* add a lnode at the beginning of the list */
void llist_add_begin(struct lnode **n, int val)
{
struct lnode *temp = NULL;

/* add new node */
temp = malloc(sizeof(struct lnode));
temp->number = val;
temp->next = *n;
*n = temp;
}

/* reverse the whole list */
void llist_reverse(struct lnode **n)
{
struct lnode *a = NULL;
struct lnode *b = NULL;
struct lnode *c = NULL;
a = *n, b = NULL;

while(a != NULL)
{
c = b, b = a, a = a->next;
b->next = c;
}

*n = b;
}

/* display the whole linked list */
void llist_display(struct lnode *n)
{
while(n != NULL)
printf(" %d", n->number), n = n->next;

printf("\n");
}

No comments:

Post a Comment