designated Initialization of a Node with a pointer (C++) - linked-list

When creating a new node in a linked list, is it legal to use designated initializers to initialize the members of the node as mentioned below?
Is there any repercussion in doing so and what would be a better way to achieve the same result?
(lang : C++)
Node *temp = new Node{.data = value, .next = NULL};
struct Node
{
int data;
Node *next;
};

I think you can use function as a constructor.
Node* newFunction(int data) {
Node* newNode = malloc(sizeof(Node));
newNode->data=data;
newNode->next=NULL;
return newNode;
}
And after that, you can use in the main part like that;
Node* newNode = newFunction(5);

Related

Linked List - Object reference not set to instance of object

I'm writing a method that adds a new Node to the back of a linked list:
public void add(string title, string director, int year, double cost)
{
Node newNode = new Node();
newNode.disc = new BluRayDisc(title, director, year, cost);
Node holder = new Node();
holder = first;
while (holder.next != null) //object reference error
{
holder = holder.next;
}
holder.next = newNode;
}
but am getting a "System.NullReferenceException: 'Object reference not set to an instance of an object.'" error thrown.
The 'first' node is initialized to null so I'm assuming that's where my problem comes from.
This is my first linked list, and this follows the example of an addToBack method I was given exactly. Does anyone have some insight on this problem?
A few issues:
first can be null, which is the case when you start with an empty linked list, and in that case first.next is an invalid reference.
About: Node holder = new Node();. It is not necessary to create a new node here, with new Node(), since in the next statement, you are throwing away that node, by doing holder = first;
Here is the correction:
public void add(string title, string director, int year, double cost)
{
Node newNode = new Node();
newNode.disc = new BluRayDisc(title, director, year, cost);
if (first == null) {
first = newNode;
return;
}
holder = first;
while (holder.next != null) //object reference error
{
holder = holder.next;
}
holder.next = newNode;
}
As you mentioned, the problem is that the variable "first" is initialized to null. It should be set the to the first node of the linked list you are constructing.

Inserting elements in list, between every two

I need to write a function that inserts a new node in a singly linked list, between every two existing nodes, with a value that is equal to the difference of the values of those two nodes.
For example if we have list 1→2→5→7 the result should be 1→1→2→3→5→2→7, because 2-1=1, 5-2=3 and 7-5=2.
Here is my attempt:
struct Node{
int v;
struct Node* next;
};
void insert(struct Node** headPtr){
struct Node* curr = *headPtr;
struct Node* new = malloc(sizeof(struct Node));
while(curr->next!=NULL){
new->v=curr->next->v-curr->v;
new->next=curr->next;
curr->next=new;
curr=curr->next;
}
}
void addRear(struct Node** headPtr, int v_new){
struct Node* new = malloc(sizeof(struct Node));
new->v=v_new;
new->next=NULL;
if(*headPtr==NULL){
*headPtr=new;
}else{
struct Node* curr = *headPtr;
while(curr->next!=NULL){
curr=curr->next;
}
curr->next=new;
}
}
void print(struct Node* head){
struct Node* curr = head;
while(curr!=NULL){
printf("%d ",curr->v);
curr = curr->next;
}
}
But when I run the following in main, I don't get any result. Here is my main code:
struct Node* head=NULL;
addRear(&head,1);
addRear(&head,2);
addRear(&head,5);
addRear(&head,7);
print(head);
printf("\n");
insert(&head);
print(head);
Two issues:
You are only creating one new node. Move the creation of the new node inside the loop.
curr=curr->next is not correct, because then curr will become equal to the new node. And so in the next iteration you will not have come any closer to the end of the list. The loop will never end. Instead you should do curr = new->next.
Here is the corrected code:
void insert(struct Node** headPtr){
struct Node* curr = *headPtr;
while (curr->next != NULL) {
struct Node* new = malloc(sizeof(struct Node)); // <---
new->v = curr->next->v - curr->v;
new->next = curr->next;
curr->next = new;
curr = new->next; // <---
}
}

Is it possible to modify the reference of an argument in Dart?

Not sure if the terminology in the title is 100% correct, but what I mean is easily illustrated by this example:
class MyClass{
String str = '';
MyClass(this.str);
}
void main() {
MyClass obj1 = MyClass('obj1 initial');
print(obj1.str);
doSomething(obj1);
print(obj1.str);
doSomethingElse(obj1);
print(obj1.str);
}
void doSomething(MyClass obj){
obj.str = 'obj1 new string';
}
void doSomethingElse(MyClass obj){
obj = MyClass('obj1 new object');
}
This will print
obj1 initial
obj1 new string
obj1 new string
But what if I wanted doSomethingElse() to actually modify what obj1 is referencing, so that the output would be:
obj1 initial
obj1 new string
obj1 new object
Is this possible in Dart, and if so, how?
No, Dart does not pass arguments by reference. (Without something like C++'s complex type system and rules, it's not clear how it would work if the caller didn't bind the argument to a variable.)
You instead could add a level of indirection (i.e., by putting obj1 inside another object, such as a List, Map, or your own class). Another possibility would be to make doSomethingElse a nested function, and then it could directly access and modify variables in the enclosing scope.
You have a reference problem in that function,
When you call doSomethingElse(obj1) in main your,
MyObject obj parameter referencing the obj1 value,
then obj you're referencing the MyClass('obj1 new objcet'),
and you're not changing the obj1 reference in the main
void doSomethingElse(MyClass obj){ // let's say we gave the parameter obj1
// here obj referencing the obj1 value
obj = MyClass('obj1 new object');
//and then it is referencing the MyClass('obj1 new object') value
//nothing change for obj1 it still referencing the same value
}
You can return that object and give reference to that object like this,
class MyClass {
String str = '';
MyClass(this.str);
}
void main() {
MyClass obj1 = MyClass('obj1 initial');
print(obj1.str);
doSomething(obj1);
print(obj1.str);
obj1 = doSomethingElse();
print(obj1.str);
}
void doSomething(MyClass obj) {
obj.str = 'obj1 new string';
}
MyClass doSomethingElse() {
return MyClass('obj1 new object');
}
output :

Size of circular list in C++ using Double Pointer

The function in resulting in an infinite loop. It is not able to return the number of nodes. Where am I going wrong?
int Count(struct node **head)
{
printf("entered");
struct node **temp;
int count = 0;
temp = &((*head)->next);
while ((&(*temp)->next) != head)
{
printf("entered");
temp = &((*temp)->next);
count++;
}
return count;
}
In the provide source code, the while-condition is referring to addresses of pointers (where the pointer is stored) and the struct node **head is pointing to a static location in the main() but (&(*temp)->next) is pointing to the allocated of the last item.
To compare items in a linked-list, you should compare pointers struct
node * instead of addresses of pointers struct node **.
In the Count() function, because the *head exists (not compared to
NULL), the counter count should start from 1 and to count all items in the circular-list, you should start by temp = &(*head); instead of the next item temp = &((*head)->next);.
Here after is a "Minimal, Complete, and Verifiable example".
#include <stdio.h>
#include <stdlib.h>
#define NODE_MAX (5)
struct node {
struct node *next;
};
int Count(struct node **head)
{
printf("entered");
struct node **temp;
int count = 1; // at least the '*head' node exists
temp = &(*head);// &((*head)->next);
while (((*temp)->next) != *head) // use '*head'
{
printf("entered");
temp = &((*temp)->next);
count++;
}
return count;
}
int main()
{
struct node array[NODE_MAX];
struct node *head, *temp;
head = &(array[0]);
temp = head;
for(int i=1;i<NODE_MAX;i++) {
temp->next = &(array[i]);
temp = temp->next;
}
temp->next = &(array[0]);
printf("\nCount = %d\n",Count(&head));
system("pause");
return (0);
}
It would be more simple to manage linked-list at pointers level like the following example:
int Count2(struct node **head)
{
printf("entered");
struct node *temp;
int count = 1;
temp = (*head); // pointers to the first
while (temp->next != *head) // direct pointer comparison
{
printf("entered");
temp = temp->next; // natural linked-list exploration
count++;
}
return count;
}

Adding a node to linked list

I have written my first datastructures code in C and I am baffled as to what I am doing wrong. I am just trying to add a node to the front of the linked list or to an empty linked list and print the list at the end and it is resulting in segmentation fault.
#include<stdio.h>
#include<stddef.h>
#include<cstdlib>
/* Node representing each node of the linked list */
struct Node {
int data;
struct Node *next;
};
/* Fist node is always null as there are no nodes in the linked list to begin with */
struct Node *first = NULL;
void add_node(int data) {
struct Node *newptr = (Node *)malloc(sizeof(Node));
// Check if the list is empty
if (first == NULL){
printf("The list is empty\n");
newptr->data = data;
newptr->next = NULL;
first = newptr;
}
else {
printf("Adding to the existing list\n");
printf("Data in the first node is %d",first->data);
}
}
void display() {
struct Node *ptr;
printf("In the display function\n");
ptr = first;
do {
printf("Printing the data in the node %d",ptr->data);
ptr= ptr->next;
}while(ptr->next != NULL);
}
int main() {
/*
* Just try and add one node
*/
int y = 100;
printf("Adding a node \n");
add_node(y);
display();
return 1;
}
I messed up the display function, I changed it a bit to have the correct output.
The following is the new display function:
void display(struct Node *first) {
struct Node *ptr;
printf("In the display function\n");
ptr = first;
do {
printf("Printing the data in the node %d",ptr->data);
ptr= ptr->next;
}while(ptr != NULL);
}

Resources