calcdude84se wrote:
Can't it just be
Code:
No need to add one more layer?
Code:
void Delete(NodePtr* head) {
NodePtr temp = *head;
NodePtr prevPtr;
while(temp != NULL) {
prevPtr = temp;
temp = temp->next;
free(prevPtr);
}
}
No need to add one more layer?
Nope, the extra layer is required.
EDIT: typedef'ing the pointer away is just confusing everyone (my apologies). Here's the new code with the *'s back ("NodePtr" is now "node_t *" which is "struct node *"):
Code:
#include <stdio.h>
#include <stdlib.h> /* Now we can use macros like NULL and EXIT_SUCCESS */
typedef struct node {
int data;
struct node *next;
} node_t; /* Now we can use the moniker "node_t" instead of "struct node" everywhere */
/* Function prototypes: */
void DisplayList(node_t * head);
void Insert(node_t * * head, int value);
void whatever(char **out);
void someotherfunc();
void Delete(node_t ** head);
int main() {
node_t * head = NULL;
Insert(&head, 10); /* Update head of list whenever you do something to the list */
Insert(&head, 20);
Insert(&head, 30);
Delete(&head);
DisplayList(head);
return EXIT_SUCCESS;
}
void DisplayList(node_t * head) {
node_t * temp;
for(temp = head; temp != NULL; temp = temp->next) { /* Make sure to check if node is NULL; trying to dereference a null pointer is very bad */
printf("%d\n",temp->data);
}
}
void Insert(node_t ** head, int value) {
node_t * newnode = (node_t *)malloc(sizeof(*newnode)); /* Create a new node */
newnode->data = value;
newnode->next = *head;
*head = newnode;
}
void Delete(node_t ** head) {
node_t ** temp = head; /* You want to make a copy of head to traverse the list */
node_t * prevPtr; /* Pointer to a node; notice there is only 1 asterisk */
while(temp != NULL) {
prevPtr = *temp; /* Dereference temp b/c it is a "double pointer" */
*temp = (*temp)->next;
free(prevPtr); /* Same here */
}
}