sort linked list alphabetikally

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • xxzl
    New Member
    • May 2015
    • 4

    sort linked list alphabetikally

    I'm trying to sort the list alphabetically , but nothing works .But when I sort of numbers the same code all works, why.
    #include <iostream>
    #include <cstring>
    #include <ctdlib>

    using namespace std;

    struct book {
    char name[100];
    char author[50];
    int pages;
    int price;
    int yt;
    };

    struct element {
    book x;
    element *next;
    };

    void add(book x, element **head){
    element * t = new element;
    t->x = x;
    t->next = *head;
    *head = t;
    }

    void addLast(book x, element ** head, element **tail) {
    element * t = new element;
    t->x = x;
    t->next = NULL;
    if (*head){
    (*tail)->next = t;
    } else {
    *head = t;
    }
    *tail = t;
    }



    void print(element *head) {
    cout << "------------------------" << endl;
    element * t = head;
    while (t != NULL) {
    cout << t->x.name<< " | " << t->x.author << " | "
    << t->x.pages << " | " << t->x.price <<"|"<<t->x.yt<< endl;
    t = t->next;
    }
    cout << endl << "------------------------" << endl;
    }
    void print(book b) {
    cout << b.name<< " | " << b.author << " | "
    << b.pages << " | " << b.price <<"|"<<b.yt<< endl;
    }
    void bS(element**hea d){
    bool change;
    element *t;
    do
    change=false;
    for(t=*head;t->next;t=t->next)
    if(strcmp(t->x.name,t->next->x.name))
    {
    strcpy(char temp,t->x.name);
    strcpy(t->x.name,t->next->x.name);
    strcpy(t->next->x.name,temp) ;
    change=true;
    }

    while(change);
    }
    int main() {

    element *head = NULL;
    element *tail = NULL;

    book b;
    strcpy(b.name, "C");
    strcpy(b.author , "D");
    b.pages = 100;
    b.price = 1500;
    b.yt=1980;
    addLast(b, &head, &tail);

    strcpy(b.name, "C");
    strcpy(b.author , "M");
    b.pages = 300;
    b.price = 2500;
    b.yt=1982;
    addLast(b, &head, &tail);

    strcpy(b.name, "K");
    strcpy(b.author , "H");
    b.pages = 120;
    b.price = 1000;
    b.yt=1975;
    addLast(b, &head, &tail);

    print(head);




    bS(&head);
    cout << "\nAfter sort :\n";
    print(head);


    //
    //
    return 0;
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    The best thing is to resubmit this code with some comments where you think you are sorting. Often just writing comments will expose errors.

    Comment

    Working...