Hello everyone can someone help me to delete the shortest word from the linked list without array?
I'am a first course student and learning pointers with linked list etc. This is my last task to do and I'am stuck.
This code finds the shortest word of the list and I need to delete that word.
I don't know how to delete that specific word.
My problem is that "del" function deletes wrong word:
void del (Node *shorter)
{
Node* temp;
temp = shorter->next;
shorter->next = temp->next;
cout<<"Deleted: "<<temp->data<<endl;
delete temp;
}
This is my full code:
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
std::vector<std::string> split(const std::string& source, const std::string& delimiters = " ") {
std::size_t prev = 0;
std::size_t currentPos = 0;
std::vector<std::string> results;
while ((currentPos = source.find_first_of(delimiters, prev)) != std::string::npos) {
if (currentPos > prev) {
results.push_back(source.substr(prev, currentPos - prev));
}
prev = currentPos + 1;
}
if (prev < source.length()) {
results.push_back(source.substr(prev));
}
return results;
}
struct Node {
std::string data;
Node* next;
};
struct Node* head = NULL;
Node* createList() {
string text;
cout << "Write text: ";
getline(cin, text);
Node *head = new Node();
head->next = NULL;
Node *current = head;
string delimiters = " ,.-':;?()+*/%$#!\"@^&";
auto results = split(text, delimiters);
bool isFirst = true;
for (const auto& word : results) {
if (isFirst) {
current->data = word;
isFirst = false;
} else {
Node *newNode = new Node();
newNode->data = word;
current->next = newNode;
current = newNode;
}
}
return head;
}
void del (Node *shorter)
{
Node* temp;
temp = shorter->next;
shorter->next = temp->next;
cout<<"Deleted: "<<temp->data<<endl;
delete temp;
}
void findShortestWord(Node* head) {
Node *current = head;
Node *shorter = head;
while (current != NULL) {
if (current->data.size() < shorter->data.size()) {
shorter->data = current->data;
} else if (current->data.size() > shorter->data.size()) {
current = current->next;
} else if (current->data.size() == shorter->data.size()) {
current = current->next;
}
}
cout << "_____________________________________________________________" << endl;
cout << "Shortest word: " << shorter->data << " |" <<endl;
cout << "_____________________________________________________________|" << endl;
del(shorter);
}
void print(Node* head)
{
if (head == NULL and cout << endl)
return;
cout<<"\nThe word you entered: ";
cout << head->data << ' ';
print(head->next);
}
int main() {
Node *head = createList();
print(head);
findShortestWord(head);
print(head);
return 0;
}