從排序的鏈接列表中刪除節點時遇到問題。我從.txt文件讀入了73個必須按字母順序排序的不同名稱。我有一個switch語句應該能夠對鏈表執行5個單獨的事情。目前我已經拿到1號和2號的工作,但不是三號。 #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文件由^^組成的內容。任何建議將不勝感激。謝謝!
我想知道的是,每個人都不斷變得教導使用'系統( 「暫停」)'... – dreamlax
指針的使用不正確,我害怕。當使用指針時,你應該處理*創建*和*刪除*。我在代碼中看不到刪除。 – Elyasin