将head声明为全局变量
#include<iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
Node* head;//将head声明为全局变量
void Insert(int x)
{
Node* temp = new Node;
temp -> data = x;
temp -> next = head;
head = temp;
}
void Print()
{
Node* temp = head;
printf("List is: ");
while(temp != NULL)
{
printf(" %d",temp -> data);
temp = temp -> next;
}
printf("\n");
}
int main()
{
head = NULL;
printf("How many numbers?\n");
int n, x;
scanf("%d",&n);
for(int i = 0; i < n; i++)
{
printf("Enter the number \n");
scanf("%d",&x);
Insert(x);
Print();
}
return 0;
}
将head定义为局部变量(Insert函数传值)
#include<iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
Node* Insert(Node* head, int x)
{
Node* temp = new Node;
temp -> data = x;
temp -> next = head;
head = temp;
return temp;
}
void Print(Node* head)
{
printf("List is: ");
while(head != NULL)
{
printf(" %d",head -> data);
head = head -> next;
}
printf("\n");
}
int main()
{
Node* head = NULL;
printf("How many numbers?\n");
int n, x;
scanf("%d",&n);
for(int i = 0; i < n; i++)
{
printf("Enter the number \n");
scanf("%d",&x);
head = Insert(head, x);
Print(head);
}
return 0;
}
将head定义为局部变量(Insert函数传地址)
#include<iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
Node* Insert(Node** pointerToHead, int x)
{
Node* temp = new Node;
temp -> data = x;
temp -> next = *pointerToHead;
*pointerToHead = temp;
}
void Print(Node* head)
{
printf("List is: ");
while(head != NULL)
{
printf(" %d",head -> data);
head = head -> next;
}
printf("\n");
}
int main()
{
Node* head = NULL;
printf("How many numbers?\n");
int n, x;
scanf("%d",&n);
for(int i = 0; i < n; i++)
{
printf("Enter the number \n");
scanf("%d",&x);
Insert(&head, x);
Print(head);
}
return 0;
}