我们的教授询问了使用链表和指针来执行 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
我是新手对不起。似乎是什么问题?谢谢。