为什么这么简单的逻辑清晰的单链会出错

C++语言 码拜 8年前 (2016-04-25) 965次浏览
#include<iostream>
#include<malloc.h>
using namespace std;
struct Node{
	int data;
	Node*Next;
};
struct List{
	Node*head;
};
Node*CreateNode();
void PushHead(List*);
int Empty(List*);
void travel(List*);
int main(){
	List a;
	a.head=NULL;
	cout<<Empty(&a)<<endl;
	PushHead(&a);
	//travel(&a);
	return 0;
}
Node*CreateNode(){
	int data;
	cin>>data;
    Node*New=(Node*)malloc(sizeof(Node));
    //new New;
	New->data=data;
	New->Next=NULL;
	return New;
}
void PushHead(List*a){
	//Node*Head=a.head;
	Node*New=CreateNode();
	New->Next=a->head->Next;
	a->head->Next=New;
}
void travel(List*a){
	Node*Head=a->head;
	if(Head==NULL){cout<<"没有元素"<<endl;return;}
	while(Head){
		if(Head==a->head){cout<<Head->Next<<" ";Head=Head->Next;}
		cout<<Head<<" ";
		Head=Head->Next;
	}
}
int Empty(List*a){
	if(a->head==NULL)return 0;
	return 1;
}
解决方案

80

head是一个指针,你没有初始化它,就去调用它的next指针,pushhead 函数中,a->head = new;

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明为什么这么简单的逻辑清晰的单链会出错
喜欢 (0)
[1034331897@qq.com]
分享 (0)