我是链接列表的新手,我在尝试删除链表的一个节点时收到此错误。
Exception thrown: Exception thrown: read access violation.
std::_String_alloc<std::_String_base_types<char,std::allocator<char> > >::_Mysize(...) returned 0xDDDDDDF1. occurred
代码:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
struct node
{
string song, artist;
node* next;
};
node* add(node *head)
{
string song, artist;
cout << "Enter song name:" << endl;
getline(cin, song);
cout << "Enter artist name:" << endl;
getline(cin, artist);
node *new_ptr = new node;
new_ptr->song = song;
new_ptr->artist = artist;
if (head == nullptr)
{
head = new_ptr;
head->next = nullptr;
}
else
{
node *ptr = head;
while (ptr->next != nullptr)
{
ptr = ptr->next;
}
ptr->next = new_ptr;
ptr->next->next = nullptr;
}
cout << "Song added." << endl;
return head;
}
node* remove(node *head)
{
if (head == nullptr)
{
cout << "There are no songs." << endl;
return head;
}
string song_to_remove;
bool found = false;
cout << "Enter song name to remove:" << endl;
getline(cin, song_to_remove);
if (head->song.compare(song_to_remove) == 0)
{
found = true;
node *temp = head;
head = head->next;
delete temp;
}
else if(head->next != nullptr)
{
node *prev_ptr = head;
node *ptr = head->next;
while (ptr != nullptr)
{
if (ptr->song.compare(song_to_remove) == 0)
{
found = true;
node *temp = ptr;
prev_ptr->next = ptr->next;
delete temp;
}
ptr = ptr->next;
prev_ptr = prev_ptr->next;
}
}
if (!found)
{
cout << "Song not found." << endl;
}
else
{
cout << "Song removed." << endl;
}
return head;
}
void print(node *head)
{
node* ptr = head;
if (ptr == nullptr)
{
cout << "There are no songs added yet." << endl;
}
else
{
while (ptr != nullptr)
{
cout << ptr->song << " by " << ptr->artist << endl;
ptr = ptr->next;
}
}
}
int main()
{
node *head = nullptr;
int option;
while (1)
{
cout << "Choose an option: Add a song (1), remove a song (2), or list all the songs (3)." << endl;
cin >> option;
cin.ignore();
if (!(option == 1 || option == 2 || option == 3))
{
cout << "Must pick either 1, 2, or 3." << endl;
continue;
}
if (option == 1)
{
head = add(head);
}
else if (option == 2)
{
head = remove(head);
}
else if (option == 3)
{
print(head);
}
}
return 0;
}
我除了remove()函数之外还有其他工作,只有当我在链表中有多个项目以及当我尝试删除除第一个项目之外的节点时,它才会出错。
答案 0 :(得分:0)
我明白了。删除bootRepackage {
classifier = 'exec'
}
后我没有break
语句,然后尝试将内容分配给ptr
。我试图让它工作,所以如果你有多个同名的歌曲,它会删除所有这些,但程序不需要那么具体。
ptr