我想編譯我的代碼,但是一旦我嘗試InsertNode,我收到一個分段和程序崩潰。請幫助C++分段錯誤
#include <iostream>
#include "Link.h"
using namespace std;
Node *createNode(){
Node *newNode = new Node;
cout<<"Enter your first name"<<endl;
cin >> newNode->firstName;
cout<<"Enter your last name"<<endl;
cin>>newNode->lastName;
cout <<"Enter your ID Number"<<endl;
cin>>newNode->idNumber;
newNode->next=NULL;
return newNode;
}
Node *insertNode (Node *list){
Node *NewNode = createNode();
//Node *NewNode = new Node;
// NewNode= createNode();
if(list == NULL){
list=NewNode;
}
else{
Node *tmp = list;
while(tmp->next!=NULL)
tmp = tmp->next;
tmp->next=NewNode;
}
return list;
}
Node *searchNode (Node *list){
bool found=false;
Node *tmp=NULL;
int ID;
cout << "Enter the ID you wish to search for: "<< endl;
cin >> ID;
if(list==NULL){
cout << "List is empty"<<endl;
return 0;
}
while(list->next!=NULL){
if(ID == (list-> idNumber)){
tmp=list;
found=true;
}
}
if(found=false){
cout<<"Not found"<<endl;
return 0;
}
return tmp;
}
Node *deleteNode (Node *list){
int ID;
if(list==NULL){
cout <<"The list is empty"<<endl;
return 0;
}
cout << "Enter the ID number you wish to delete:" << endl;
cin >> ID;
if(list->idNumber==ID){
Node *temp;
temp=list->next;
//free(list);
return temp;
}
list->next = deleteNode(list->next);
return list;
}
void printList(Node *list){
Node* tmp=list;
if(tmp==NULL){
cout<<"The list is empty"<<endl;
}
cout<< tmp-> firstName<<endl;
cout << tmp->lastName<<endl;
cout <<tmp->idNumber<<endl;
}
預先感謝您的任何幫助
它們被賦予用來調用任何這些函數 加入我的主菜單只是爲了告訴
#include "Link.h"
#include <iostream>
using namespace std;
void DisplayMenu();
int main(){
int answer=0;
Node *NewNode = new Node;
//NewNode = NULL;
do{
DisplayMenu();
cin >> answer;
if(answer==1){
insertNode(NewNode);
}
else if(answer==2){
deleteNode(NewNode);
}
else if(answer==3){
printList(NewNode);
}
else if(answer==4){
searchNode(NewNode);
}
else if(answer==5){
cout << "Goodbye" << endl;
}
}while(answer!=5);
return 0;
}
void DisplayMenu(){
cout<< "1. Insert a node"<<endl;
cout<<"2. Delete a node"<<endl;
cout<<"3. Print List"<<endl;
cout<<"4. Search a node-search a node and print information for a student."<<endl;
cout<<"5. Quit the program"<<endl;
}
你是如何調用'insertNode'? – 2015-02-24 03:27:42
除了'new',這幾乎不是C++。你能不能粘貼你如何調用'insert'? – Jagannath 2015-02-24 03:28:25
是你的Node類的下一個成員初始化爲null? – matt 2015-02-24 03:31:36