我遇到了一个Node的问题,在列表前添加新的节点后,无法遍历Node列表。在列表前添加新节点后,我无法遍历Node列表。添加的结果不是动作。除非我把函数 "Add_a_another_Node_in_first_list "的主体放在函数main里面,否则就可以了。谁能给我解释一下为什么?
#include<iostream>
using namespace std;
struct LinkedList
{
int data;
struct LinkedList *pnext;
}; typedef struct LinkedList Node;
void Create_a_Node(int data, Node *head)
{
head->data = data;
head->pnext = NULL;
}
void Add_a_Node_in_first_list(Node *second, Node *head, Node *third)
{
head->pnext = second;
head->data = 0;
second->data = 1;
second->pnext = third;
third->data = 2;
third->pnext = NULL;
}
void Add_a_another_Node_in_first_list(int data, Node *head)
{
Node *new_node = new Node;
new_node->data = data;
new_node->pnext = head;
head=new_node;
}
void Traversal_Nodes(Node *ptr)
{
while (ptr != NULL)
{
cout << ptr->data << "\t" << ptr;
cout << endl;
ptr = ptr->pnext;
}
}
int main()
{
Node *head = NULL;
Node *second = NULL;
Node *third = NULL;
head = new Node;
second = new Node;
third = new Node;
Create_a_Node(1, head);
Add_a_Node_in_first_list(second,head, third);
Traversal_Nodes(head);
Add_a_another_Node_in_first_list(-1, head);
cout << "\nAfterwards\n";
Traversal_Nodes(head);
}
当调用这个函数时 Add_a_another_Node_in_first_list()
的值,你正在改变 head
. 因此传递头指针的引用。
请看下面的实现。
#include<iostream>
using namespace std;
struct LinkedList
{
int data;
struct LinkedList *pnext;
}; typedef struct LinkedList Node;
void Create_a_Node(int data, Node *head)
{
head->data = data;
head->pnext = NULL;
}
void Add_a_Node_in_first_list(Node *second, Node *head, Node *third)
{
head->pnext = second;
head->data = 0;
second->data = 1;
second->pnext = third;
third->data = 2;
third->pnext = NULL;
}
void Add_a_another_Node_in_first_list(int data, Node* *head)
{
Node* new_node = new Node;
new_node->data = data;
new_node->pnext = *head;
*head=new_node;
}
void Traversal_Nodes(Node *ptr)
{
while (ptr != NULL)
{
cout << ptr->data << "\t" << ptr;
cout << endl;
ptr = ptr->pnext;
}
}
int main()
{
Node *head = NULL;
Node *second = NULL;
Node *third = NULL;
head = new Node;
second = new Node;
third = new Node;
Create_a_Node(1, head);
Add_a_Node_in_first_list(second,head, third);
Traversal_Nodes(head);
Add_a_another_Node_in_first_list(-1, &head);
cout << "\nAfterwards\n";
Traversal_Nodes(head);
}
输出:
0 0x171e670
1 0x171e5b0
2 0x171e4d0
Afterwards
-1 0x171e410
0 0x171e670
1 0x171e5b0
2 0x171e4d0