sorting in linked lists

This is a discussion on sorting in linked lists within the C Programming forums, part of the General Programming Boards category; Can we sort elements inside the linked list using qsort, if not what must we do to sort elements inside ...

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    15

    sorting in linked lists

    Can we sort elements inside the linked list using qsort, if not what must we do to sort elements inside the linked list?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    typedef struct elephant
    {
    	char name[10];
    	struct elephant *next;
    }ELEPHANT;
    void print_elephants( const ELEPHANT* ptr);
    int main()
    {
    	/* define 3 ELEPHANT variables and 1 pointer to elephant. */
    	ELEPHANT elephant1, elephant2, elephant3, *start;
    
    	/* Store elephants' name */
    	strcpy( elephant1.name, "Jake" );
    	strcpy( elephant2.name, "Elmer" );
    	strcpy( elephant3.name, "Kent" );
    
    	/* link elephants */
    	elephant1.next = &elephant2;	/* Edna points to Elmer */
    	elephant2.next = &elephant3;	/* Eloise is last */
    
    	/* start contains the address of the first node */
    	start = &elephant1;
    	print_elephants( start );
    	return EXIT_SUCCESS;
    	
    }
    
    void print_elephants( const ELEPHANT* ptr)
    {
    	int count = 1;
    	printf( "\n\n\n");
    	while ( ptr != NULL )
    	{
    		printf( "\nElephant number %d is %s.", count++, ptr -> name );
    		ptr = ptr -> next;
    	}
    }

  2. #2
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    No, you can't use qsort.

    Write your swap function to swap to nodes. Write a compare function that compares two nodes. Then write a sort function which uses these two functions.

    Or use google to find out how to sort linked lists!

  3. #3
    Registered User
    Join Date
    Apr 2004
    Posts
    173
    Try implementing mergesort, since it works rather nicely with LLs.
    The cost of software maintenance increases with the square of the programmer's creativity.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Linked Lists 101
    By The Brain in forum C++ Programming
    Replies: 5
    Last Post: 07-24-2004, 04:32 PM
  2. Sorting Linked Lists (code not concept)
    By Newbie Magic in forum C++ Programming
    Replies: 2
    Last Post: 05-11-2004, 08:57 AM
  3. Map file formats and linked lists
    By Spitball in forum Game Programming
    Replies: 2
    Last Post: 03-04-2004, 10:32 PM
  4. need help w/ linked lists
    By MKashlev in forum C++ Programming
    Replies: 11
    Last Post: 08-05-2002, 08:57 PM
  5. doubly linked lists
    By qwertiop in forum C++ Programming
    Replies: 3
    Last Post: 10-03-2001, 06:25 PM

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