问题遇到的现象和发生背景
带头结点的单链表输出时为什么没有指向所应指向的指针也能输出正确结果,真的很懵逼(调试的时候发现的)
问题相关代码,请勿粘贴截图
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef int datatype;
typedef struct node
{
datatype data;
struct node *next;
} node;
typedef node *linklist;
node *init()
{
node *head;
head = (node *)malloc(sizeof(node));
head->next = NULL;
return head;
}
void output1(node *head)
{
node *s;
int i = 0;
if (!s)
{
cout << "空的";
return;
}
cout << "链表为:";
while (s)
{
cout << s->data << ' ';
i++;
if (i % 10 == 0)
cout << endl;
s = s->next;
}
cout << endl;
}
void createbystack1(node *head)
{
node *p = head;
node *s;
datatype x;
cout << "请输入若干数据,以0为结束符" << endl;
cin >> x;
while (x)
{
s = new node;
s->data = x;
if (head->next == NULL)
{
head->next = s;
s->next = NULL;
p = s;
}
else
{
head->next = s;
s->next = p;
p = s;
}
cin >> x;
}
}
int main()
{
node *head;
head = init();
createbystack1(head);
output1(head);
system("pause");
return 0;
}
运行结果及报错内容
请输入若干数据,以0为结束符
1 2 3 4 5 6 0
链表为:6 5 4 3 2 1
请按任意键继续. . .
真的不懂为什么能运行成功,希望得到您的解惑,,谢谢