0 like 0 dislike

0 like 0 dislike
by (3.2k points)

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);

int main(void)

{

int i;

for(i = 1; i <= NUM_ITEMS; i++)

{

}

printf("I will now reverse the linked list\n");

return 0;

}

{

struct Node *iterator;

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));

currentNode->data = nodeValue;

if(position == 1)

{

return;

}

for (i = 0; i < position - 2; i++)

{

nodeBeforePosition = nodeBeforePosition->next;

}

currentNode->next = nodeBeforePosition->next;

nodeBeforePosition->next = currentNode;

}

{

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 */

}

Explanation for the Reverse List Method

We start the previousNode out as NULL, since we know on the ﬁrst iteration of the loop, if we are looking for the node before the ﬁrst head node, it will be NULL. The ﬁrst 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.