Reputation: 113
The structure of the node is as followed:
struct Node {
int value;
Node *next;
};
// construct a new node
Node * cons( int x, Node* p) {
return new Node{x, p};
}
Now if I were to type in my main body:
Node *p;
p = cons(3,nullptr);
p = cons(2,p);
p = cons(1,p);
p = cons(4,p);
Is there a better value to start off with for my first node instead of nullptr?From what I understand this is 4 Nodes in order. Is that correct? Node value 3 is the first on the list. So this function would search my linklist in order as in goes to view node value 3, 2,1,4,then empty node.
//search linklist in order for value x
bool searchInOrder(int x, Node *p){
while(p->next != nullptr){
if(x == p->value)
return true;
p = p->next;
}
return false;
}
Upvotes: 0
Views: 64
Reputation: 206707
Question:
Is there a better value to start off with for my first node instead of
nullptr
?
Answer:
That is the best way to create the first node of a linked list.
Question:
From what I understand this is 4 Nodes in order. Is that correct? Node value 3 is the first on the list. So this function would search my linklist in order as in goes to view node value 3, 2,1,4,then empty node.
Answer:
Yes there are 4 Nodes. However, the Node with value 3 is not the first Node in the list.
After
p = cons(3,nullptr);
The list is:
+---+ +-----+
+ p + ---> | 3 | ---> NULL
+---+ +-----+
After
p = cons(2,p);
The list is:
+---+ +-----+ +-----+
| p | ---> | 2 | ---> | 3 | ---> NULL
+---+ +-----+ +-----+
After
p = cons(4,p);
The list is:
+---+ +-----+ +-----+ +-----+ +-----+
| p | ---> | 4 | ---> | 1 |---> | 2 | ---> | 3 | ---> NULL
+---+ +-----+ +-----+ +-----+ +-----+
Upvotes: 4