Thread: sorting in linked lists

  1. #1
    Registered User
    Join Date
    Mar 2005

    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?

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    typedef struct elephant
    	char name[10];
    	struct elephant *next;
    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(, "Jake" );
    	strcpy(, "Elmer" );
    	strcpy(, "Kent" );
    	/* link elephants */ = &elephant2;	/* Edna points to Elmer */ = &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
    Cape Town
    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
    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, 11: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