【发布时间】:2020-06-02 15:04:15
【问题描述】:
为什么每次循环运行时 temp 的地址(在 main 的 while 循环中)都相同 我试图插入一个链表,然后显示然后输出中间元素,但最初在显示它时运行了一个无限循环,只显示第一个元素。在插入和 llist.add_ele_to_beg(&temp); 后打印地址它每次都打印相同的地址!为什么会这样?
#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;
}
【问题讨论】:
-
temp需要是动态分配的指针变量(例如使用malloc)而不是本地变量。 -
为什么你认为每次都应该不一样?
标签: c++ memory linked-list