Dec 3, 2013 at 6:06am UTC
HellO!
I am currently learning Linked List; I'm rusty & need practice and lots of leads.
Let me start with the following task I would like to get done:
I would like to create a list and return the i'th value in the node of the list.
I don't know how to start it..any pointers or leads would be sweet.
Last edited on Dec 5, 2013 at 5:40pm UTC
Dec 3, 2013 at 6:43am UTC
What do you already have? Do you have a list structure? Or are you trying to create that first?
Dec 4, 2013 at 1:35am UTC
This is what I have: I'm stuck in actually getting a node at a specific index from the linked list. I don't know how to implement it properly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#include <iostream>
using namespace std;
template <typename T>
class Node {
protected :
struct Nodelist {
Nodelist *next;
T val;
Nodelist(T value1, Nodelist *next1 = NULL) : val(value1), next(next1) {}
};
Nodelist *head;
public :
Node() {head = NULL; }
~Node();
void add(T val);
void remove(T val);
void displayList();
T& get(int i);
};
template <typename T>
T& Node<T>::get(int i) {
int len = 0;
Nodelist *temp = head->next;
while ((temp = temp->next) != NULL) {
if (i == len++)
return temp;
}
return NULL;
}
template <typename T>
void Node<T>::add(T val) {
if (head == NULL)
head = new Nodelist(val);
else {
Nodelist *nodePtr = head;
while (nodePtr->next != NULL)
nodePtr = nodePtr->next;
nodePtr->next = new Nodelist(val);
}
}
I tried implementing like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <iostream>
#include "node.h"
using namespace std;
int main () {
Node<int > head;
head.add(2);
head.add(3);
head.add(7);
head.add(12);
cout << endl << endl;
cout << endl << "The i'th value: " << endl;
head.get(2);
cout << endl << endl;
return 0;
}
But I am getting errors like:
node.h:41:11: error: invalid initialization of reference of type 'int&' from expression of type 'Node<int>::Nodelist*'
node.h:43:10: error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'long int'
I would appreciate any help!
Last edited on Dec 5, 2013 at 6:59pm UTC
Dec 4, 2013 at 2:14am UTC
Your code seems to imply you are returning a pointer from get(), but you are declaring it to return a reference. Which did you mean?
Dec 4, 2013 at 2:37am UTC
I am just trying to return by reference, at least that's my attempt.
Last edited on Dec 5, 2013 at 6:53pm UTC