Sunday 8 September 2013

Sunday 8 September 2013

Reverse a LinkedList



Simple  Program to Reverse a LinkedList

#include <stdio.h>
#include <stdlib.h>

struct node{
    struct node *link;
    int data;
    };
 
    void insert(struct node **,int);
    void display(struct node *);
    int count(struct node *);

    void delete(struct node **,int);
    void append(struct node **,int);
     void reverse(struct node **);
    int main(){
        struct node *s;
        s=NULL;
      
    
        insert(&s,10);
        insert(&s,20);
        insert(&s,40);
        insert(&s,50);

        reverse(&s);
  
        display(s);
      
        return 0;
    }
 
    void insert(struct node **s,int num){
        struct node *temp;
        temp=(struct node*)malloc(sizeof(struct node));
        temp->data=num;
        temp->link=*s;
        *s=temp;
    }
    void display(struct node *s){
 
        while(s!=NULL){
            printf("%d \n",s->data);
            s=s->link;
        }
        printf("\n");
    }

int count(struct node *s){
        int i;
        i=0;
        while(s!=NULL){
          
            s=s->link;
            i++;
        }
        printf("%d",i);
    }

void delete(struct node **s,int num){
    struct node *temp,*old;
    temp=(struct node *)malloc(sizeof(struct node));
       temp->data=num;
      temp->link=*s;
      *s=temp;
      
       free(temp);
       
   }

void append(struct node **s,int num){
    struct node *temp;
    temp=(struct node *)malloc(sizeof(struct node));
    temp->data=num;
    temp->link=NULL;
    *s=temp;
}


void reverse(struct node **s)  {

 struct node *a = NULL;
 struct node *b = NULL;
 struct node *c = NULL;
 a = *s, b = NULL;

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

 *s = b;
}
output:
Executing the program....
Before Reverse

50 
40 
20 
10 

$demo
after reverse
10 
20 
40 
50 

No comments:

Post a Comment