EQuestionAnswers.com Computer/Electronics Questions and Answers
C, C++, VC++, COM/DCOM, DLL and more
#Login #Sign up  Facebook Twitter TGoogle+
 

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;
};
10  int main(int argc, char* argv[])
11  {
12    node * head;
13    node * tail;
14    node * temp;
15    node * prev;
16    node * current;
17    node * next;
18 
19    /*Construct 4 nodes in the list*/
20    temp = (node *)malloc(sizeof(node));
21    temp->value = 1;
22    /*This is the head*/
23    head = temp;
24 
25    temp->next = (node *)malloc(sizeof(node));
26    temp = temp->next;
27    temp->value = 2;
28 
29    temp->next = (node *)malloc(sizeof(node));
30    temp = temp->next;
31    temp->value = 3;
32 
33    temp->next = (node *)malloc(sizeof(node));
34    temp = temp->next;
35    temp->value = 4;
36    temp->next = NULL;
37 
38    /*This is the last, tail*/
39    tail = temp;
40 
41    /*Print all elements, starting from head*/
42    temp = head;
43    while(temp)
44    {
45      printf("element %x, value %d\n", temp, temp->value);
46      temp = temp->next;
47    }
48 
49    printf("Reversing the linked list\n");
50    /*Reverse the linked list*/
51    prev = NULL;
52    current = next = head;
53    while(current)
54    {
55      next = current->next;
56      current->next = prev;
57      prev = current;
58      current = next;
59      
60 
61    }
62    /* Now list has been reversed and tail becomes head. Print all elements, starting from tail*/
63    temp = tail;
64    while(temp)
65    {
66      printf("element %x, value %d\n", temp, temp->value);
67      temp = temp->next;
68    }
69    return 0;
70  }
71 
72 

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