I want to create with the existing singly linked list a new list but backwards. First, print the original list, then backwards.
The progress so far:
#include <stdio.h>
#include <stdlib.h>
struct Digits {
int digit;
struct Digits* next;
};
void displayNodes(struct Digits*);
void freeNodes(struct Digits* );
struct Digits* backwardsList(struct Digits*, int);
struct Digits* appendNodeFront(struct Digits*, struct Digits*);
struct Digits* appendNode(struct Digits*, struct Digits*);
struct Digits* createNode(int);
int main(void) {
int digitNodes, digits;
struct Digits* newNode, * headNode, * endNode, * backwards;
printf("Nodes: ");
scanf("%d", &digitNodes);
for(int i = 0; i < digitNodes; i++) {
printf("Enter numebr: ");
scanf("%d", &digits);
newNode = createNode(digits);
if(i == 0) {
headNode = endNode = newNode;
}
else {
endNode = appendNode(endNode, newNode);
}
}
backwards = backwardsList(headNode, digits);
displayNodes(backwards);
displayNodes(headNode);
freeNodes(headNode);
freeNodes(backwards); // no need for this statement right?
}
struct Digits* backwardsList(struct Digits* headNode, int digits) {
struct Digits* headNodeCpy = headNode, * endNode, * newNode;
for(int i = 0; i < digits; i++) {
newNode = createNode(headNodeCpy->digit);
headNodeCpy = headNodeCpy->next;
if(i == 0) endNode = newNode;
else endNode = appendNodeFront(newNode, endNode);
}
return endNode;
}
struct Digits* appendNodeFront(struct Digits* newNode, struct Digits* endNode) {
newNode->next = endNode;
return newNode->next;
}
void freeNodes(struct Digits* headNode) {
int i = 0;
struct Digits* headNodeCpy = headNode;
struct Digits* tmp;
while(headNodeCpy != NULL) {
tmp = headNodeCpy->next;
free(headNodeCpy);
headNodeCpy = NULL;
if(headNodeCpy == NULL) printf("Node %d cleared\n", i);
else printf("Error, node %d not cleared\n", i);
headNodeCpy = tmp;
i++;
}
printf("\n");
}
void displayNodes(struct Digits* headNode) {
struct Digits* headNodeCpy = headNode;
while(headNodeCpy != NULL) {
printf("%d\n", headNodeCpy->digit);
headNodeCpy = headNodeCpy->next;
}
printf("\n");
}
struct Digits* appendNode(struct Digits* endNode, struct Digits* newNode) {
endNode->next = newNode;
return endNode->next;
}
struct Digits* createNode(int digits) {
struct Digits* newNode;
newNode = (struct Digits*)malloc(sizeof(struct Digits));
newNode->digit = digits;
newNode->next = NULL;
return newNode;
}
I think that the error occurs in the backwardsList()
function, because i didn't set the "end" of this backwards list like i do up in main()
.
Function where the error might occurs:
struct Digits* backwardsList(struct Digits* headNode, int digits) {
struct Digits* headNodeCpy = headNode, * endNode, * newNode;
for(int i = 0; i < digits; i++) {
newNode = createNode(headNodeCpy->digit);
headNodeCpy = headNodeCpy->next;
if(i == 0) endNode = newNode;
else endNode = appendNodeFront(newNode, endNode);
}
return endNode;
}
Any help appreciated!