This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
3
Creating a new list in a function?
Post Flair (click to view more posts with a particular flair)
Post Body
So, I have a singly linked list. And I want to go through it, and get all the even numbers. And put the even numbers in a new list. And return the new head. The original list should remain untouched.
What I have tried:
(Just my function):
struct node_t* new_list_head;
struct node_t* even_nodes(struct node_t** old){
new_list_head = nullptr;
struct node_t* curr_node = *old;
bool found = false;
struct node_t* new_list_curr;
while (curr_node != nullptr){
if (curr_node->v % 2 == 0)
{
struct node_t new_node;
new_node.v = curr_node->v;
new_node.next = nullptr;
if (!found)
{
found = true;
new_list_head = &new_node;
}
else
{
new_list_curr->next = &new_node;
};
new_list_curr = &new_node;
};
curr_node = curr_node->next;
};
return new_list_head;
};
Everything (probably TMI):
#include <iostream>
struct node_t
{
unsigned v;
struct node_t* next;
};
struct node_t* new_list_head;
struct node_t* even_nodes(struct node_t** old){
new_list_head = nullptr;
struct node_t* curr_node = *old;
bool found = false;
struct node_t* new_list_curr;
while (curr_node != nullptr){
if (curr_node->v % 2 == 0)
{
struct node_t new_node;
new_node.v = curr_node->v;
new_node.next = nullptr;
if (!found)
{
found = true;
new_list_head = &new_node;
}
else
{
new_list_curr->next = &new_node;
};
new_list_curr = &new_node;
};
curr_node = curr_node->next;
};
return new_list_head;
};
void print(struct node_t* head){
while (head != nullptr){
std::cout << head->v << '\n';
head = head->next;
}
}
int main(){
struct node_t a;
struct node_t b;
struct node_t c;
struct node_t d;
a.v = 6;
a.next = &b;
b.v = 17;
b.next = &c;
c.v = 7;
c.next = &d;
d.v = 4;
d.next = nullptr;
struct node_t* head = &a;
//print(head);
struct node_t* new_list = even_nodes(&head);
//print(head);
print(new_list);
}
So, the new_list prints the last even number and then a random number, then segmentation fault. (10, 4181723112)
Edit:I found the solution. I used the new operator.
struct node_t* new_node = new struct node_t;
And changed the rest of the code accordingly. This solved my problem.
Author
Account Strength
100%
Account Age
5 years
Verified Email
Yes
Verified Flair
No
Total Karma
16,411
Link Karma
6,422
Comment Karma
9,490
Profile updated: 1 day ago
Posts updated: 1 year ago
Subreddit
Post Details
We try to extract some basic information from the post title. This is not
always successful or accurate, please use your best judgement and compare
these values to the post title and body for confirmation.
- Posted
- 2 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/cpp_questio...