Objective:
1.To understand linked list concepts
2.To write a solution for a given linked list related problem.
Exercise
:
1.Write a non-recursive function that counts the nodes in a linked list
.
Partial Solution:
//Suppose that
the Node structure is as follows
Class
Node {
Public:
DataType
data;
Node * next;
};
//Then,your non-recursive function is as follows:
int
NumNodes(Node* first)
{
int
count = 0;
Node
* ptr = first;
while
(ptr != 0)
{
Count++;
ptr = ptr->next;
}
return
count;
}
Problem:
1.Write a driver program to test your non-recursive node-counter function that you have written in the exercise.
2.Write a recursive function that counts the nodes in a linked list. Then, write a driver program to test your recursive node-counter function.
I am new to c++ programming and using Dev C++ as I used c programming last time. Is there any solution for this question as i am having alot of problem with it. Any help will be helpful thanks
class LinkedList {
struct Node {
int x;
Node *next;
};
//public member
public:
//constructor
LinkedList(){
head = NULL; //set head to NULL
}
//this prepends a new value at the beginning of the list
void addValue(int val){
Node *n = new Node();
n->x = val;
n->next = head;
head = n;
}
int popValue (){
Node *n = head;
int ret = n->x;
head = head->next;
delete n;
return ret;
}
//private member
private:
Node *head; //this is the private member variable. it's just a pointer
};
int main()
{
LinkedList list; //list is the OBJECT of the CLASS (TO GAIN ACCESS TO THE CLASS)
//all the FUNCTION is assigned to the OBJECT 'list'
list.addValue(5);
list.addValue(10);
list.addValue(20);