I'm trying to write a function called 'set' that sets the value of the i'th cell to val on my linkedList, and then returns the previous contents. I am stuck on it due to compiling errors:
template <typename T>
T set(Node<T> *head, int i, const T &val) {
for(int n = 0; n < i; n++)
if(head == val) {
val = i;
}
return val;
}
#endif
When I try to call it in the main() I get these errors:
node_utils.h: In function ‘T set(Node<T>*, int, const T&) [with T = int]’:
node_demo.cpp:26:38: instantiated from here
node_utils.h:161:2: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
node_utils.h:162:3: error: assignment of read-only reference ‘val’
So, I understand that I can't compare head & val on my if-statement -- But what do I do?
Line 5: You can't assign i to val since val is const. Also, no guarantee that T is type int.
Line 7: You need to assign head to head->next so you're pointing to the next node.
You need some check that you don't exceed the number of entries in the list.
You also need some way to signal to the caller that val was not found in the list.
1 2 3 4 5 6 7 8 9 10 11
template <typename T>
T set(Node<T> *head, int i, const T &val)
{ T temp;
for (int n = 0; n < i && head != NULL; n++)
if (n == i-1)
{ temp = head->data; // old value
head->data = val; // assign new value
return temp;
}
return ???; // Didn't find i'th node
}
template <typename T>
T set(Node<T> *head, int i, const T &val) {
if(!val) throw"Not found in the list";
Node<T> *temp;
for(int n = 0; n < i && head != NULL; n++)
if(n == i-1) {
temp = head->data;
head->data = val;
return temp;
}
return 0; // didn't write NULL because I guess I can't return NULL
reference?
}
Understanding that I needed to assign head to head->next to point to the next node. But even after calling set in my .cpp file I'm getting his error:
In file included from node_demo.cpp:4:0:
node_utils.h: In function ‘T set(Node<T>*, int, const T&) [with T = int]’:
node_demo.cpp:26:39: instantiated from here
node_utils.h:164:3: error: invalid conversion from ‘int’ to ‘Node<int>*’ [-fpermissive]
node_utils.h:166:10: error: invalid conversion from ‘Node<int>*’ to ‘int’ [-fpermissive]
Same problem returning 0. Will work only if T is a scalar.
Edit: Regarding errors above. Note that in the code I posted, temp is not a pointer. In your code, you have temp as a pointer. That's going to cause problems. e.g. Line 7 You can't assign a value (head->data) to a pointer. Line 9, you can't return a pointer where a value is expected.