Reputation: 709
I know this is seriously basic stuff, but I for the life of me can't seem to understand how I would go about doing this:
Q: Given the following struct definition for a Node:
struct Node
{
int value;
Node* next;
};
And given the declaration:
Node* head;
The following Linked List of Nodes has been constructed, with the head pointer assigned to the Node object 3:
head ----> 3 ----> 9 ----> 34 ----> -5 ----> NULL
Write a single C++ statement that will store the value 34 in the 3rd Node in the variable result:
int result =
Where would be a good place to start? Is this asking me to add an element to the list, or is it adding an entirely new node to the list? So confused!!
Upvotes: 1
Views: 85
Reputation: 121
Linked lists employ a chain concept, where each chain-link along the entire length of the chain is connected at the front of each link.
People represent this in various ways. One example is:
struct Node {
int value;
Node* front;
};
Or:
struct Node {
int value;
Node* next;
};
When you establish the head of a linked list, you are creating the first node in the chain:
Node* head;
head = NULL; // this is an empty linked list
Whenever you want to add a node (or "link") to the chain, you pass along the new node to "Head", which keeps track of the chain:
void newNode(int value, Node* head)
{
Node *node;
node = new Node*; // or (Node*)malloc(sizeof(Node));
node->value = value;
node->next = head;
head = node;
}
Using this concept, you can add any number of links to your chain. Thomas and warun have good examples of this. Hope this helps.
Upvotes: 2
Reputation: 453
head->next->next
will point to the third node in the linked list.
So,
int result = head->next->next->data;
will store the value in the third node in the list.
The question is asking you to read the third node and store it's value in result.
Upvotes: 2
Reputation: 2279
example for a loop.
Node* temp = head;
int number = 300; //the place you are looking for
if(temp)
{
int i;
for(i = 0 ; i< number && temp->next != nullptr ;i++)
{
temp = temp->next;
}
if(i == 300)
{
//found you value;
result = temp->value;
}
}
Upvotes: 1