Google Add

Search

Write a Program/Code to Reverse a Linked List

Assume you have a linked list

Input - 1->4->5->6

Output - 6->5->4->1

In Input head points to a node whose value is 1 and the address node which contains 6 point to NULL.

In Output things are just reversed head point to node whose value is 6 and node which has value 1 points to NULL.



Algorithm to Reverse a Linked List


1. First we need to traverse a linked list.

2. Reverse a links means the address node points to next node to prev, prev to current and current to next.

Program to Reverse a Linked List


#include <stdio.h>

struct node{
    int data;
    struct node* next;
};

struct node* head;

void insert_node(int data){
    
    struct node* newnode=(struct node*)malloc(sizeof(struct node*));
    newnode->data = data;
    newnode->next = head;
    
    head = newnode;
}

void reverse_node(){
    
    struct node *prev,*next,*current;
    current = head;
    
    while(current!=NULL){
        
        next = current->next;
        current->next = prev;
        prev = current;
        current=next;
    }
    head = prev;
    
}

void print(){
    
    struct node* p;
    p = head;
    
    while(p!=NULL){
        printf("%d\n",p->data);
        p=p->next;
    }
    printf("\n");
}
Void main()
{

  head = NULL;
  insert_node(6);
  insert_node(5);
  insert_node(4);
  insert_node(1);

  print();
  reverse_node();
  print();

}
Problem on Linked List

Best Books on Data Structures


Data Structure Books Available on Flipkart

Data Structure Books Available on Amazon India

Data Structure Books on Amazon

No comments:

Post a Comment