why is the address of temp (in the while loop in main) the same everytime the loop runs i am trying to insert into a linked list and then display and then output the middle element but initially in displaying it ran an infinite loop only displayint the first element. On printing the address after inserting and llist.add_ele_to_beg(&temp); its priting the same address each time ! why is this happening ?
#include<iostream>
#include <unistd.h>
using namespace std;
class LinkedList;
class Node
{
private:
Node* next;
int value;
friend class LinkedList;
public:
Node(int ele) // constructor - declared in private section
// to prevent other classes creating objects of this class,
// only this class can create the object
{
next = nullptr;
value = ele;
}
};
class LinkedList
{
private:
Node* head;
public:
LinkedList()
{
head = nullptr;
}
void add_ele_to_beg(Node *temp)
{
// Node *temp = new Node(); // dynamically alloctg Node object
// temp->value = x;
temp->next = this->head;
this->head = temp;
}
void display()
{
Node *h = this->head;
while(h)
{
cout << h << endl;
cout << h->value << endl;
h = h->next;
cout << h << endl;
cout << h->value << endl;
exit(0);
}
}
int findMiddle()
{
Node *fast, *slow = this->head;
if(!slow)
{
return -1;
}
if(!slow->next)
{
return slow->value;
}
if(!slow->next->next)
{
return slow->value;
}
// n > 2
fast = head->next->next;
while(1)
{
slow = slow->next;
if(!fast->next)
{
if(!fast->next->next)
{
fast = fast->next->next;
}
else
{
break;
}
}
else
{
break;
}
}
return slow->value;
}
};
int main()
{
LinkedList llist;
int n;
cout << "enter n" << endl;
cin >> n;
// create a dummy node
cout << "enter elements to be inserted in the beg" << endl;
int ele;
while(n--)
{
cin >> ele;
Node temp(ele); // obj node created and ctor initialises
llist.add_ele_to_beg(&temp); // sending address of node to make change to
cout << &temp << endl;
// node (passing by reference)
}
llist.display();
cout << llist.findMiddle();
cout << endl;
return 0;
}