用C++实现一个单链表,在第123行输入想删除的结点时出现问题,cin语句直接被跳过。经检查发现,上一次使用cin时(creat函数中),最后一个输入字符为结束符。下次再使用cin时因为遇到结束符,直接无视输入,所以直接跳过了。解决方法:在下一次需要cin时先调用cin.clear进行输入重置(第121行)。
#include<iostream>
#include<string>
using namespace std;
struct node
{
string s;
node* next;
};
node* creat()
{
string st;
node *head, *now;
head = new node;
now = head;
while(cin >> st)
{
now->s = st;
now->next = new node;
now = now->next;
}
now->next = NULL;
return head;
}
int getlen(node* n)
{
int length=0;
if(n == NULL)
return 0;
else
{
while(n->next)
{
length++;
n = n->next;
}
return length;
}
}
void printlist(node* n)
{
if(n == NULL)
cout << "list is empty !" << endl;
else
{
while(n->next)
{
cout << n->s << " ";
n = n->next;
}
cout << n->s << endl;
}
}
node* deletenode(node *head, string st)
{
node *now,*temp;
now = head;
if(head->s == st)
{
head = head->next;
delete now;
now = NULL;
return head;
}
while(now->s != st && now->next != NULL)
{
temp = now;
now = now->next;
}
if(now->s == st)
{
temp->next = now->next;
delete now;
now = NULL;
return head;
}
else
{
cout << "can not find " << st << endl;
return head;
}
}
node* insertnode(node* head, int pos)
{
return head;
}
void main()
{
string deletes;
cout << "please input data: " << endl;
node *head = creat();
cout << "length of list: " << getlen(head) << endl;
printlist(head);
cout << "delete: " << endl;
cin.clear(); //重置错误输入
//cin.sync(); //清空缓冲区
cin >> deletes;
deletenode(head, deletes);
printlist(head);
}