【发布时间】:2018-05-10 04:57:38
【问题描述】:
我目前正在课堂上学习如何使用链表。我只能添加、删除、显示和排序数据。
是否可以编辑用户输入的数据?
请看一下代码,这是一种可能的修改方式吗?
修改列表值我实现了一个简单的提示机制,但是有个小问题:
用户输入年龄后程序立即停止工作。
void node::update()
{
int updateAge;
cout << "Please enter age: ";
cin>>updateAge;
int ch;
int a;
node *current;
node *temp;
node *start_ptr;
if (start_ptr == NULL)
cout << "No record to update!" << endl;
else
{
current = start_ptr;
while((current!=NULL) && (current->temp->age!=updateAge))
{
current=current->next;
}
if (current==NULL)
{cout<<"The Requested age is Not Found" << endl;}
else if(current->temp->age==updateAge)
{
cout<<"What Information You Want To Update?" << endl;
cout<<"1. Name" << endl;
cout<<"2. Height" << endl;
cin>>ch;
system("cls");
switch(ch)
{
case 1 :
{
cout << "Enter New Name: ";
cin.ignore();
getline(cin, current->temp->name);
break;
}
case 2 :
{
cout<<"Enter New Height: ";
cin >> current->temp->height;
break;
}
default:
{
cout<<"Wrong Input! Please choose again: ";
cin>>ch;
}
}
cout<<"RECORD UPDATED !";
}
}
}
struct list
{
list *head, *tail;
list *next;
};
class node
{
private:
std::string name; // Name
int age; // Age in integer
float height; // In meters
public:
node *next; // Pointer to next node
node *head, *tail;
node *start_ptr = NULL; // Start Pointer (root)
node *temp;
node *temp2;
node *pNextValue;
node* prev; // empty header
node* current;
void update();
void printList();
void delete_end_node();
void search();
void sort_age();
void deletebyAge();
node()
{
head = NULL;
tail = NULL;
}
void getInput()
{
temp = new node;
cout << "Name: ";
cin >> temp->name;
cout << "Age: ";
cin >> temp->age;
cout << "Height: ";
cin >> temp->height;
cout<<"\n";
temp->next = NULL; // Sets the node to be the last node
if (start_ptr == NULL)
start_ptr = temp;
else
{
temp2 = start_ptr; // We know temp2 is not NULL - list not empty!
while (temp2->next != NULL) // The loop will terminate when temp2
temp2 = temp2->next; // points to the last node in the list
// Move to next link in chain
temp2->next = temp; // Sets the pointer from that last node to point
// to the node that has just declared
}
} // End of getInput() function
}; //End of class
【问题讨论】:
-
是的,你想要的都是可能的。由于这看起来像家庭作业,但我将把它留给你。您提供的代码 sn-p 是否可以完成这项工作也只有您可以决定。
-
@UlrichEckhardt 不,这不是作业。我只是使用此代码来了解有关如何在课堂上使用链表的更多信息。 :)
-
只是想指出输入处理不是很健壮。如果用户输入的值不是
1或2怎么办?我建议你实现一个用户交互功能,这将帮助你确保用户输入是有效的。祝你好运,欢迎来到 StackOverflow! -
哦,我忘了@RannLifshitz
-
您能否发布您在应用程序崩溃时收到的错误信息?您还可以提供用于执行的输入吗?
标签: c++ class linked-list