Write a C program to reverse a single linked list without any second list.

Source Code

/* RLL.C: Reverse a single linked list without any second list. */

#include "stdafx.h"
#include<malloc.h>
struct node
{
  int value;
  struct node *next;
};
int main(int argc, char* argv[])
{
  node * head;
  node * tail;
  node * temp;
  node * prev;
  node * current;
  node * next;

  /*Construct 4 nodes in the list*/
  temp = (node *)malloc(sizeof(node));
  temp->value = 1;
  /*This is the head*/
  head = temp;

  temp->next = (node *)malloc(sizeof(node));
  temp = temp->next;
  temp->value = 2;

  temp->next = (node *)malloc(sizeof(node));
  temp = temp->next;
  temp->value = 3;

  temp->next = (node *)malloc(sizeof(node));
  temp = temp->next;
  temp->value = 4;
  temp->next = NULL;

  /*This is the last, tail*/
  tail = temp;

  /*Print all elements, starting from head*/
  temp = head;
  while(temp)
  {
    printf("element %x, value %d\n", temp, temp->value);
    temp = temp->next;
  }

  printf("Reversing the linked list\n");
  /*Reverse the linked list*/
  prev = NULL;
  current = next = head;
  while(current)
  {
    next = current->next;
    current->next = prev;
    prev = current;
    current = next;
    

  }
  /* Now list has been reversed and tail becomes head. Print all elements, starting from tail*/
  temp = tail;
  while(temp)
  {
    printf("element %x, value %d\n", temp, temp->value);
    temp = temp->next;
  }
  return 0;
}


Find More from our code collection
Armstrong number, binary number to a decimal number, bubble sort, decimal number to binary number, factorial of the given number factors, fibonacci numbers, HCF and LCM, matrix, mergesort, salary of the employee. palindrome, quadratic equation, star patterns, series etc. and much more...
#Return to Example Source Code