#include <iostream>
using namespace std;
struct Node
{
int item; // storage for the node's item
Node* next; // pointer to the next node
};
Node* addNode(Node*& head, int data , int& count)
{
Node * q; // new node
q = new Node; // allocate memory for the new mode
q->item = data; // inserting data for the new node
q->next = head; // point to previous node ?? how would i do that? ( am i doing it correctly?)
count++; // keep track of number of node
head = q;
return q;
}
int main()
{
int a, count=0;
int data;
bool repeat;
Node *head= NULL;
//^^ assuming thats creating the first node ^^
do
{
cout << "please enter the data for the next node" <<endl;
cin >> data;
addNode(head, data, count);
cout << "do you wish to enter another node? (enter true or false)" << endl;
cin >>repeat;
}
while (repeat == true);
// assuming this is the print function
while(head != NULL)
{
cout << "output" << temp->item << endl;
cout << temp->next << endl;
}
system("pause");
return 0;
}
好吧,我尝试在列表中添加一个新元素,我如何像 LIFO 内存(堆栈)一样移动头部,以便最后一个元素位于最顶部..
任何帮助将不胜感激!指针和节点最近在搅乱我的大脑....
最佳答案
temp
是一个未初始化的指针。所以——
temp-> item = a; // temp is not initialized or pointing to a memory location
// that has Node object to use operator ->
首先,temp
需要使用new
分配内存位置。
temp = new Node;
temp -> item = a;
现在给它分配head
。同样在 while
循环中也为子节点分配内存。并在程序终止前使用delete
将所有从child获取的资源返回给head。
关于c++ - 链表C++,问题自学,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5689432/