patterncppMinor
In-place reversal of a singly linked list
Viewed 0 times
placesinglyreversallistlinked
Problem
As suggested in The 2nd Monitor, I'd like a review of this in-place reversal of a singly linked-list:
#include
struct node {
int data;
node *next;
};
node *reverse(node *list) {
node *prev = NULL;
node *next;
while (list) {
next = list->next;
list->next = prev;
prev = list;
list = next;
}
return prev;
}
void show_list(node *list) {
while (list != NULL) {
std::cout data next;
}
}
int main() {
node *list = NULL;
for (int i=0; inext = list;
n->data = i;
list = n;
}
std::cout << "As built: ";
show_list(list);
list = reverse(list);
std::cout << "Reversed: ";
show_list(list);
return 0;
}Solution
-
You don't use
In this case, have an identical
With these two loops, you might as well have a constant to hold the number of nodes to use, so that you can make sure the same number is used.
-
You don't need to have
You don't use
delete after allocating nodes with new, resulting in a memory leak. As a general rule, delete should be used in the same way new was used.In this case, have an identical
for loop and use delete on each node:for (int i=0; i<10; i++) {
delete n;
}With these two loops, you might as well have a constant to hold the number of nodes to use, so that you can make sure the same number is used.
-
You don't need to have
return 0 at the end of main(). Reaching the end implies successful completion, and the compiler will insert this return for you.Code Snippets
for (int i=0; i<10; i++) {
delete n;
}Context
StackExchange Code Review Q#45918, answer score: 8
Revisions (0)
No revisions yet.