Create and reverse a doubly linked list.
#include <stdio.h>
#include <stdlib.h>
struct doubleLinkedList
{
int item;
struct doubleLinkedList *nextNode;
struct doubleLinkedList *prevNode;
};
//Function that reverses the linked list
void reverse(struct doubleLinkedList **head)
{
struct doubleLinkedList *tempNode = NULL;
struct doubleLinkedList *currentNode = *head;
while (currentNode != NULL)
{
tempNode = currentNode->prevNode;
currentNode->prevNode = currentNode->nextNode;
currentNode->nextNode = tempNode;
currentNode = currentNode->prevNode;
}
if(tempNode != NULL )
*head = tempNode->prevNode;
}
//Function to create double linked list
void push(struct doubleLinkedList** head, int data)
{
struct doubleLinkedList* node = (struct doubleLinkedList*) malloc(sizeof(struct doubleLinkedList));
node->item = data;
node->prevNode = NULL;
node->nextNode = (*head);
if((*head) != NULL)
(*head)->prevNode = node ;
(*head) = node;
}
/* Function to print doubly linked list */
void printList(struct doubleLinkedList *node)
{
while(node!=NULL)
{
printf("%d ", node->item);
node = node->nextNode;
}
}
int main()
{
struct doubleLinkedList* node = NULL;
push(&node, 1);
push(&node, 2);
push(&node, 3);
push(&node, 4);
printf("\n The Original Double Linked List ");
printList(node);
reverse(&node);
printf("\n The Reversed Linked list ");
printList(node);
getchar();
}
Comments
Leave a comment