Hi,
I was trying to reverse a list by swapping the previous and the next address of the current list. The logic seems to be right, but i cannot point as to where exactly the segmentation fault occurs.
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
Node *next;
Node *prev;
}Node;
Node* createNode(int data)
{
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
}
void BuildList(Node **root, int data)
{
Node *temp = (*root);
if(temp == NULL)
{
(*root) = createNode(data);
}
else
{
while(temp->next != NULL)
{
temp = temp->next;
}
Node *newNode = createNode(data);
temp->next = newNode;
newNode->prev = temp;
}
}
void reverseListSwap(Node **root)
{
Node *current = (*root);
Node *prev = NULL;
Node *next = current->next;
Node *loop = (*root);
while(current->next != NULL)
{
Node *temp = current;
temp->next = prev;
temp->prev = next;
prev = current;
next = current->next;
current = current->next;
}
current->next = prev;
current->prev = NULL;
(*root) = current;
}
int main()
{
Node *root = NULL;
BuildList(&root, 45);
BuildList(&root, 46);
BuildList(&root, 47);
BuildList(&root, 48);
BuildList(&root, 49);
reverseListSwap(&root);
printList(&root);
return 0;
}