我们的教授询问如何使用链表和指针来执行ADT列表操作。编译它时没有错误。但每个函数都会在一个无限循环中结束。
#include <stdlib.h>
#include <iostream>
using namespace std;
char choice;
struct node
{
int value;
struct node *link;
};
typedef struct node *list;
list *head;
void print(list *head)
{
list ptr=NULL;
if (*head!=NULL)
{
for (ptr=*head; ptr->link!=NULL; ptr=ptr->link)
cout<< ptr->value <<" ";
cout<<ptr->value;
} //if
else
cout<<"NOTHING TO PRINT!";
} //print
void add(list *head)
{
int num;
list ptr;
cout<<"What do you want to add: ";
cin>>num;
cout<<"Options: "<<endl<<"A. Addtail"<<endl<<"B. Addhead"<<endl
<<"Choice : ";
cin>>choice;
switch(choice)
{
case 'a':
case 'A':
{
list newnode,ptr;
ptr=*head;
newnode=(list)malloc(sizeof(struct node));
while(ptr->link!=NULL)
ptr=ptr->link;
ptr->link=newnode;
newnode->value=num;
newnode->link=NULL;
break;
} // case a
case 'b':
case 'B':
{
list newnode;
newnode = (list)malloc(sizeof(struct node));
newnode->value=num;
newnode->link=*head;
*head=newnode;
break;
} // case b
} // switch
print(head);
} // add
void deleted(list *head)
{
list ptr;
cout<<"Options: "<<endl<<"A. Deletetail"<<endl<<"B. Deletehead"<<endl
<<"Choice : ";
cin>>choice;
switch(choice)
{
case 'a':
case 'A':
{
list ptr,ptr2;
ptr=*head;
if(*head!=NULL)
{
while(ptr->link!=NULL)
{
ptr2=ptr;
ptr=ptr->link;
} //while
free(ptr);
ptr2->link=NULL;
}//if
else
cout<<"Nothing to delete!";
}//case a
case 'b':
case 'B':
{
list ptr;
if(*head!=NULL)
{
ptr=*head;
*head=ptr->link;
free(ptr);
}
else
cout<<"Nothing to delete!";
}//case b
}//switch
print(head);
}//delete
void empty(list *head)
{
if (*head !=NULL)
cout<<"The list is not Empty"<<endl<<endl;
else
cout<<"The List is Empty"<<endl<<endl;
}//empty
void makenull(list *head)
{
*head = NULL;
print(head);
}//makenull
main ()
{
int dota=0;
while(dota<10)
{
cout<<"ADT List Operations:"<<endl<<"A. Add"<<endl<<"B. Delete"<<endl<<
"C. Empty"<<endl<<"D. Make Null"<<endl<<"E. Print"<<endl<<"F. Exit"<<endl
<<"Choice: ";
cin>>choice;
switch(choice)
{
case 'a':
case 'A': {add(head);break;}
case 'b':
case 'B': {deleted(head);break;}
case 'c':
case 'C': {empty(head);break;}
case 'd':
case 'D': {makenull(head);break;}
case 'e':
case 'E': {print(head);break;}
case 'f':
case 'F': {dota=100;break;}
}//switch
}//while
cout<<"Do you want to try again?"<<endl<<"Choice : ";
cin>>choice;
if(choice =='Y' || choice =='y')
{makenull(head); main();}
system("pause");
}//main
对不起,我是个新手。问题出在哪里?谢谢
不错的代码,试试这个
在void makenull(list*head)函数中,您有一个无限循环,因为您没有松开头部的链环。所以它显然是一个无限循环。所以试试这个。。。
void makenull(list *head)
{
(*head)->value = NULL;//make data empty
(*head)->link = NULL;//make link empty
print(head);
}//makenull
希望这能奏效。
case 'a':
case 'A':
{
list newnode,ptr;
ptr=*head;
newnode=(list)malloc(sizeof(struct node));
while(ptr->link!=NULL)
ptr=ptr->link;
ptr->link=newnode;
newnode->value=num;
newnode->link=NULL;
break;
} // case a
当你进入这个程序时,你必须首先使其为NULL,这样头才是NULL。但请参阅添加代码。如果head为NULL,则永远不会将head指针实际设置为有效节点。。。这就是为什么你在add-to-tail上崩溃的原因。我认为其他路径也有类似的问题。内存从未正确初始化。