Getting started
Function pointers
Operators
Data types
Arrays
Undefined behavior
Random numbers
Preprocessor and macros
Signal handling
Variable arguments
Files and I/O streams
Assertion
Linked lists
Generic selection
X-macros
Function parameters
Pointers
Structs
Sequence points
Command-line arguments
Aliasing and effective type
Compilation
Identifier scope
Bit-fields
Strings
Comman pitfalls
Error handling
Implicit and explicit conversions
Type qualifiers
Valgrind
Typedef
Selection statements
Declaration vs. definitio
Standard math
Boolean
Literals for numbers, characters and strings
Storage classes
Declarations
Formatted Input/Output
Compound literals
Inline assembly
Threads native
Initialization
Structure padding and packing
Memory management
Implementation-defined behaviour
Atomics
Iteration statements, loops, for, while, do-while
Enumerations
Jump Statements
Create and include header files
Testing frameworks
ctype.h characters classification
Pass 2D-arrays to functions
Side effects
Multi-character character sequences
Constrains
Inlining
Unions
Multi-threading
Common idioms and developer practices
Inter-process communication (IPC)
Comments
Contributors

Reversing a linked list

suggest change

You can also perform this task recursively, but I have chosen in this example to use an iterative approach. This task is useful if you are inserting all of your nodes at the beginning of a linked list. Here is an example:

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

#define NUM_ITEMS 10

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

void insert_node(struct Node **headNode, int nodeValue, int position);
void print_list(struct Node *headNode);
void reverse_list(struct Node **headNode);

int main(void) {
  int i;
  struct Node *head = NULL;

  for(i = 1; i <= NUM_ITEMS; i++) {
    insert_node(&head, i, i);
  }
  print_list(head);

  printf("I will now reverse the linked list\n");
  reverse_list(&head);
  print_list(head);
  return 0;
}

void print_list(struct Node *headNode) {
  struct Node *iterator;

  for(iterator = headNode; iterator != NULL; iterator = iterator->next) {
    printf("Value: %d\n", iterator->data);
  }
}

void insert_node(struct Node **headNode, int nodeValue, int position) {
  int i;
  struct Node *currentNode = (struct Node *)malloc(sizeof(struct Node));
  struct Node *nodeBeforePosition = *headNode;

  currentNode->data = nodeValue;

  if(position == 1) {
    currentNode->next = *headNode;
    *headNode = currentNode;
    return;
  }

  for (i = 0; i < position - 2; i++) {
    nodeBeforePosition = nodeBeforePosition->next;
  }

  currentNode->next = nodeBeforePosition->next;
  nodeBeforePosition->next = currentNode;
}

void reverse_list(struct Node **headNode) {
  struct Node *iterator = *headNode;
  struct Node *previousNode = NULL;
  struct Node *nextNode = NULL;

  while (iterator != NULL) {
    nextNode = iterator->next;
    iterator->next = previousNode;
    previousNode = iterator;
    iterator = nextNode;
  }

  /* Iterator will be NULL by the end, so the last node will be stored in
  previousNode.  We will set the last node to be the headNode */
  *headNode = previousNode;
}

Explanation for the Reverse List Method

We start the previousNode out as NULL, since we know on the first iteration of the loop, if we are looking for the node before the first head node, it will be NULL. The first node will become the last node in the list, and the next variable should naturally be NULL.

Basically, the concept of reversing the linked list here is that we actually reverse the links themselves. Each node’s next member will become the node before it, like so:

Head -> 1 -> 2 -> 3 -> 4 -> 5

Where each number represents a node. This list would become:

1 <- 2 <- 3 <- 4 <- 5 <- Head

Finally, the head should point to the 5th node instead, and each node should point to the node previous of it.

Node 1 should point to NULL since there was nothing before it. Node 2 should point to node 1, node 3 should point to node 2, et cetera.

However, there is one small problem with this method. If we break the link to the next node and change it to the previous node, we will not be able to traverse to the next node in the list since the link to it is gone.

The solution to this problem is to simply store the next element in a variable (nextNode) before changing the link.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents