15 September 2009

single linked list in C

list *reverse(list *current)
{
list *prev = NULL;
list *next = NULL;

while(current)
{
next = current->next; //tricky: save the next node
current->next = prev; //point current to previous
prev = current;
current = next;
}

return prev;
}

--------------------llist.c--------------------
#include <stdio.h>
#include <stdlib.h>

typedef struct list{
int val;
struct list *next;
}list;


list *insert(list *head, int val)
{
list *new = (list*)malloc(sizeof(list));
new->val = val;
new->next = head;

return new;
}

void print(list *head)
{
while(head)
{
printf("%d->", head->val);
head = head->next;
}

printf("NULL\n");
}

list *reverse(list *current)
{
list *prev = NULL;
list *next = NULL;

while(current)
{
next = current->next; //tricky: save the next node
current->next = prev; //point current to previous
prev = current;
current = next;
}

return prev;
}

int main()
{
list *head = NULL;

head = insert(head, 10);
head = insert(head, 12);
head = insert(head, 20);
head = insert(head, 17);
head = insert(head, 25);
head = insert(head, 3);
head = insert(head, 75);
head = insert(head, 49);
head = insert(head, 32);
printf("before reverse: ");
print(head);

head = reverse(head);
printf("after reverse: ");
print(head);

return 0;
}
-----------------------------------------------

Output:
before reverse: 32->49->75->3->25->17->20->12->10->NULL
after reverse: 10->12->20->17->25->3->75->49->32->NULL

No comments:

Post a Comment