Sorting by int (low to high) in linked list

This is a discussion on Sorting by int (low to high) in linked list within the C++ Programming forums, part of the General Programming Boards category; Hello, I need to sort the following by ID as I enter them into a linked list by while loop. ...

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    1

    Sorting by int (low to high) in linked list

    Hello, I need to sort the following by ID as I enter them into a linked list by while loop. So far I can build through the list, but I'm not sure how to sort by ID as they are entered:


    Albert 1000 55.5 150
    Babs 3000 60 110
    Freida 1150 71 175.5
    Big_Al 2000 77 244
    Tiny 1550 44 77


    Code:
        nodeType *first, *newNode, *last;
        
        first = NULL;
        last = NULL;
        
        while (inFile)
        {
            newNode = new nodeType; //01x
            inFile >> newNode->info.firstname;
            inFile >> newNode->info.id;
            inFile >> newNode->info.height;
            inFile >> newNode->info.weight;
            newNode->link = NULL;
            
            if (first == NULL) //first case init
            {
                first = newNode;
                last = newNode;
            }
            else
            {
                last->link = newNode;
                last = newNode;
            }
            
    }

    Thanks for the help!
    Last edited by smallrubberfeet; 11-27-2011 at 03:49 PM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,848
    Well basically, you walk the list to find the place to insert the item.
    Code:
    prev = NULL, curr = head;
    while ( curr && curr->info.id > newNode->info.id ) {
      prev = curr;
      curr = curr->next;
    }
    You then have 3 cases
    - before the start
    - somewhere in the middle
    - after the end.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorting a linked list
    By aw1742 in forum C Programming
    Replies: 1
    Last Post: 10-20-2011, 01:46 PM
  2. Linked List Sorting
    By oddworld in forum C Programming
    Replies: 4
    Last Post: 04-27-2007, 11:42 PM
  3. sorting in linked list
    By esi in forum C Programming
    Replies: 8
    Last Post: 04-24-2007, 03:03 PM
  4. Sorting a linked list
    By thoseion in forum C Programming
    Replies: 6
    Last Post: 11-13-2006, 10:34 AM
  5. Sorting a linked list.
    By Jamie32 in forum C++ Programming
    Replies: 3
    Last Post: 10-29-2002, 04:24 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21