我无法从已排序的链表中删除节点。我从.txt文件中读取了73个必须按字母顺序排序的不同名称。我有一个switch语句,它应该能够对链接列表执行5个单独的操作。目前,我已经获得了1号和2号的工作权,但还没有得到3号工作。#3希望我能够从链接列表中删除一个名称。输入要删除的名称后,我的代码将不会显示任何内容。因此,我假设我在deleteAfter函数方面遇到问题。谁能给我一个暗示,为什么会这样?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct node{
string name;
node *next;
};
node *A = NULL;
void addnode(string newname){
node *add,
*last,
*current;
add = new node;
add->name = newname;
if (A == NULL){
add->next = A;
A = add;
}else{
current = A;
last = A;
while (current && current->name < newname){
last = current;
current = current->next;
}
if (current == A){
/* Insert before 1st node */
add->next = A;
A = add;
}
else{
/* Insert between last and current
or at the end of the list */
last->next = add;
add->next = current;
}
}
}
void deleteName(string name)
{
node *curr;
node *nextNode;
curr = A;
nextNode = curr;
while(curr){
if(curr -> next -> name == name){
nextNode = curr -> next;
curr -> next = nextNode -> next;
}
}
}
void display()
{
node *curr;
curr = A;
while(curr){
if(A == NULL){break;}
cout << A->name << endl;
A = A->next;
}
}
int main(){
int input, count;
count = 0;
ifstream dataFile;
dataFile.open("Data.txt");
string item;
string name;
while(dataFile)
{
dataFile >> item;
addnode(item);
count++;
}
cout << "1. Display the linked list\n";
cout << "2. Display the length of the list\n";
cout << "3. Delete name from the list\n";
cout << "4. display the length of a section of the list\n";
cout << "5. Print out section of list\n";
cin >> input;
switch (input)
{
case 1:
display();
break;
case 2:
cout << "There are " << count - 1 << " names in the list\n";
break;
case 3:
cout << "Type in the name that you want to be deleted: ";
cin >> name;
deleteName(name);
display();
break;
case 4:
break;
case 5:
break;
}
system("PAUSE");
return 0;
}
这是我到目前为止的代码。您会注意到,在我的主要功能中,我从名为“ Data.txt”的文件中读取输入。
joe
bob
harry
mary
brian
tom
jerry
bullwinkle
pam
ellis
dale
bill
barrack
george
gertrude
zack
zeus
apollo
gemini
greg
larry
meriam
webster
thomas
stewart
dianna
theresa
billyjoe
carl
karl
charles
karla
donna
tena
kerry
howard
johnson
ulyssess
paul
peter
issaac
marvin
dudz
chuck
ellie
anny
judy
matt
ross
dan
robert
kim
eric
junkun
ghassan
cris
raymond
avery
roy
halley
mitzee
ziggy
rocky
twirly
max
huey
dewy
hongkongfooey
clarence
lala
sammy
fred
francis
这就是txt文档的组成部分^^。任何建议将不胜感激。谢谢!
您在访问next时没有检查它是否不为null,也没有在列表中进行迭代。另外,您应该在找到它后中断它(除非您想删除所有实例,并且应该删除该节点,否则将泄漏内存。此外,您将无法删除第一个元素,因为您永远不会您可以根据需要添加特定的检查,以处理更改根节点的需要。
if (A != nullptr && A->name == name)
{
node *toBeDeleted = A;
A = A->next;
delete toBeDeleted;
return;
}
while(curr && curr->next){
if(curr->next->name == name){
nextNode = curr->next;
curr->next = nextNode->next;
delete nextNode;
break;
}
curr = curr->next;
}
当然,如果要删除名称的所有实例,则需要删除return和break语句。
您的显示功能也将清空列表。您需要设置curr,而不是A:
void display()
{
node *curr;
curr = A;
while(curr){
cout << curr->name << endl;
curr = curr->next;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句