Play and learn 300 000+ tabs online

Saturday, June 19, 2010

Reverse a Linked List Program


#include<stdio.h>
#include<stdlib.h>
struct list
{
    int month;
    struct list *next;
};
typedef struct list node;

void init(node* record)
{
    record->next=NULL;
}
void addnode(node* record,int d)
{
    node* fresh;
    fresh=(node *)malloc(sizeof(node));
    fresh->month=d;
    fresh->next=record->next;
    record->next=fresh;
}
void print(node *record)
{
    node* temp;
    temp=(node *)malloc(sizeof(node));
    for(temp=record->next;temp;temp=temp->next)
        printf(" %d",temp->month);
}
void reverse(node* record)
{
    node* temp;node* temp1;node* temp2;
    temp=(node *)malloc(sizeof(node));
    temp1=(node *)malloc(sizeof(node));
    temp2=(node *)malloc(sizeof(node));
    temp=record;temp1=temp->next;temp2=temp1->next;
    temp->next->next=NULL;
    while(temp2!=NULL)
    {
        temp=temp1;
        temp1=temp2;
        temp2=temp1->next;
        temp1->next=temp;
    }
    record->next=temp1;
}
int main(void)
{
    node* start;
    node* start1;
    start=(node *) malloc(sizeof(node));
    init(start);
    int i=0;
    for(i=10;i>=0;i--)
        addnode(start,i);
    print(start);
    reverse(start);
    printf("n");
    print(start);
    return 0;
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.