2016-04-25 4 views
0

У меня есть домашняя задача, где я должен сортировать связанные элементы списка (строки) после первого символа в строке. Пример:C++ - Link Insert List Sorting (String elements)

От: Pineapple-> Apple-> аш> Abc-> Pearl-> Bonfire-> Бал

Кому:A pple-> SH-> BC->В onfire->В all->Р ineapple->Р графа (только первый символ)

Я сделал функцию:

void insertionSort() 
{ 
    first = current; 
    Node* insertionPointer = first; 
    current = current -> next; 
    for (start(); !end(); next()){ // Running through all list nodes 
     while (current != NULL) { 
      insertionPointer = first; 
      while(insertionPointer->next != current) { 
       if (insertionPointer->data.at(0) > current-> data.at(0)){ // Trying to sort strings alphabetically 
                      // (after only first char) 
        string temp = current->data; 
        current->data = insertionPointer->data; 
        insertionPointer->data = temp; 
       } 
       else { 
        insertionPointer = insertionPointer->next; 
       } 
      } 
     } 
    } 
} 

Но я получаю ошибку сегментации - Я предполагаю, что означает, что я пытаюсь получить некоторую информацию, что я не могу получить доступ? Кроме того, я не уверен, что:

if (insertionPointer->data.at(0) > current-> data.at(0)) 

Будет ли сравнивать строки первого символа? Я просто пытаюсь экспериментировать здесь. :( Просто, чтобы быть уверенным, я опубликую ниже также весь мой код, чтобы вы могли видеть, как я структурировал списки и другие функции. Я новичок в этом материале - вся информация будет полезна.

Полная программа код:

#include <iostream> 
#include <fstream> 
#include <string> 
#include <string.h> 
using namespace std; 
class Node 
{ 
public: 
string data; 
Node *next; 
Node (string city) { data = city; next = NULL; }; 
}; 
class List 
{ 
protected: 
    Node *first, *last; 
public: 
    Node *current; 
public: 
    List() { first = last = current = NULL; }; 

void add_element (string city); 
void delete_element(); 
~List(); 

bool is_empty() { return (first == NULL); }; 
void start() { current = first; }; 
bool end() { return (current == NULL); }; 
void next(){if (!end())current = current -> next;}; 
void print(); 

void insertionSort() 
{ 
first = current; 
Node* insertionPointer = first; 
current = current -> next; 
for (start(); !end(); next()){ // Running through all list nodes 
while (current != NULL) { 
    insertionPointer = first; 
    while(insertionPointer->next != current) { 
         if (insertionPointer->data.at(0) > current->data.at(0)){ // Trying to sort strings alphabetically 
                        // (after only first char) 
         string temp = current->data; 
         current->data = insertionPointer->data; 
         insertionPointer->data = temp; 
         }else{ 
         insertionPointer = insertionPointer->next; 
         } 
    } 
} 
    } 
} 


}; 


int main() 
{ 
string s; 
List l; 

l.add_element("Pineapple"); 
l.add_element("Apple"); 
l.add_element("Ash"); 
l.add_element("Abc"); 
l.add_element("Pearl"); 
l.add_element("Bonfire"); 
l.add_element("Ball"); 


l.print(); 
cout << endl; 
l.insertionSort(); 
l.print(); 



return 0; 
} 

void List::add_element (string city) 
{ 
Node *p = new Node (city); 
if (first == NULL) first = last = p; 
else last = last -> next = p; 
current = p; 
}; 

void List::delete_element() 
{ 
Node *p = first; 
if(!is_empty()) 
{ if (current == first) current = first-> next; 
first = first -> next; 
delete p; 
if(is_empty())last = NULL; 
} 
}; 
void List::print() 
{ 
for (start(); !end(); next()) 
{ 
cout << current->data << endl; 
} 
cout << endl; 
}; 
List::~List() 
{ 
while (!is_empty()) 
{ 
delete_element(); 
}; 
cout << "All memory of nodes deleted!"<< endl; 
}; 
+0

Пожалуйста, не вход из неизвестного файла (к нам). Просто вызовите необходимые функции списка с известными, жестко закодированными значениями. Вот как вы должны тестировать, и особенно если другие хотят дублировать проблему. Если 'add_element (" abc "); add_element ("123"); add_element ("Джо"); add_element ("Боб"); insertionSort(); 'не работает, чтение из файла не будет работать. – PaulMcKenzie

+0

@PaulMcKenzie Я принял ваш совет и изменил свою основную функцию в коде. Я до сих пор не могу решить: 1. Ошибка сегментации 2. «if (insertionPointer-> data.at (0)> current-> data.at (0)) {« Будет ли этот оператор сортировать только после первого символа строк? – Maartin1996

+0

Ваша логика - все неправильно. ваш 'add: element' должен вставить отсортированный. – Thomas

ответ

0

Ваша программа, скорее всего, сбой здесь:

while(insertionPointer->next != current) { 

потому insertionPointer стала нулевой, когда выполняется

insertionPointer = insertionPointer->next; 

изменить условие цикла к

while(insertionPointer && insertionPointer->next != current) { 
+0

Все еще дает мне ошибку сегментации. – Maartin1996

+0

ваш код полностью изменен, и он не падает, см. [Ваш код в прямом эфире] (http://coliru.stacked-crooked.com/a/9573530a60cc760a). он не сортирует .. – Thomas