Thread: swap elements in a linked list.

  1. #1
    Learner Axel's Avatar
    Join Date
    Aug 2005
    Posts
    335

    swap elements in a linked list.

    I want to sort a link last based on a few criterias. If a nodes x element is less than y then they should be swapped. I need to do this to all elements in the list till it is sorted from smallest to largest. The first step was i attempted to write a swap method as follows;

    Code:
    void swap(charNode **x, charNode **y)
    {
    
       charNode*temp;
       temp = *x; // save x temporarly.
       x = y; // swap y and x position
       *y = temp; // place x after y
    
    }
    which miserably failed. I just tried modifying one of the swap methods that i use for an array. For some reason when i pass the address of the "start" node and start->next nodes after i print it; it does not reflect anything.. Any ideas?
    Last edited by Axel; 10-15-2006 at 02:32 AM.

  2. #2
    Learner Axel's Avatar
    Join Date
    Aug 2005
    Posts
    335
    my full code as follows...
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct charNode
    {
       char petName[12];
    
       struct charNode *next;
    };
    
    typedef struct charNode charNode;
    
    void addElement(charNode **start, char *petName);
    void printList(charNode *start);
    charNode* newNode(char *petName);
    void getString(charNode *start);
    void swap(charNode **x, charNode **y);
    
    int main()
    {
       charNode *start = NULL;
    
       getString(start);
      
       return 0;
    }
    
    
    void getString(charNode *start)
    {
    
         addElement(&start, "(1)Cat");
         addElement(&start, "(2)Dog");
         addElement(&start, "(3)Horse");
         
         swap(&start->next, &start);
         printList(start);
    }
    
    void addElement(charNode **start, char *petName)
    {
    
       charNode *temp,*prev, *loc;
       int i;
    
       temp = newNode(petName);
    
    
       if (*start == NULL)
       {
          *start = temp;
       }
    
       else
       {
          loc = *start;
          prev = NULL;
    
           for (i=0; loc != NULL; i++)
           {
       
               	prev = loc;
    			loc = loc->next;
            }
    	      if (prev == NULL)
             {     
                *start = temp;
             }
             else
             {
                prev->next = temp;  
             }
       }
      
    
    }
    
    
    charNode* newNode(char *petName)
    {
    
       charNode *temp;
    
       temp = (charNode *) malloc(sizeof(charNode));
       if (temp == NULL)
       {
          printf("WARNING - Memory allocation error\n");
          exit(EXIT_FAILURE);
       }
    
    
      strcpy(temp->petName, petName);
    
    
       temp->next = NULL;
    
       return temp;
    }
    
    
    void printList(charNode *start)
    {
    
       while (start != NULL)
       {
    
          printf("%s\n", start->petName);
          start = start->next;
       }
    }
    
    void swap(charNode **x, charNode **y)
    {
    
       charNode *temp;
       temp = *x; // save x temporarly.
       x = y; // swap y and x position
       *y = temp; // place x after y
    
    }

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,662
    > x = y; // swap y and x position
    Assuming everything else is OK, this would be
    *x = *y; // swap y and x position
    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.

  4. #4
    Registered User
    Join Date
    Oct 2004
    Posts
    151
    Pass in two pointers to charNode, and do a byte-for-byte exchange of their information fields (i.e. char petName[12]).

    The alternative approach is to mess around with pointers and actually change the logical sequence of the nodes, and that is not a pretty thing.
    Last edited by zx-1; 10-15-2006 at 03:27 AM.
    System: Debian Sid and FreeBSD 7.0. Both with GCC 4.3.

    Useful resources:
    comp.lang.c FAQ | C++ FQA Lite

  5. #5
    Learner Axel's Avatar
    Join Date
    Aug 2005
    Posts
    335
    Quote Originally Posted by zx-1

    The alternative approach is to mess around with pointers and actually change the logical sequence of the nodes, and that is not a pretty thing.
    this is what i'm trying to do now. I'm almost there but i have a few problems:

    The following code will sort the animals in alphabetical order. The ONLY problem i'm having is if i have the last node come previously alphabetically then it does not order it i.e:
    Code:
     addElement(&start, "Dog");
         addElement(&start, "Android");
         addElement(&start, "Bat");

    the result is :

    Code:
    Androd
    Dog
    Bat

    Code:
    charNode *swap(charNode *start)
    {
    
       charNode *temp = NULL;
       charNode *prev = NULL;
       charNode *current = start;
    
       if (start!=NULL)
       {
          if (start->next != NULL)
          {
             prev = start;
             current = start;
    
             while (current != NULL)
             {
                if ( strcmp(current->petName, start->petName) <0)
                {
                   prev->next = current->next;     
                   temp = start;      
                   start = current;      
                   start->next = temp;   
                                        
                }
             
                else
                   prev = current;
                   current = current->next;
             }
          }
       }
       return start;
    }
    by the way the code above can be used with the code previously posted by replacing the swap function and by putting:

    Code:
    start = swap(start);
    before the printList statement...

  6. #6
    Fear the Reaper...
    Join Date
    Aug 2005
    Location
    Toronto, Ontario, Canada
    Posts
    625
    You're not quite swapping correctly. To swap two elements in a linked list, you need to exchange their "next" pointer, but you also need to exchange their predecessor's "next" pointer. You seem to be understanding the former, but without the latter, your linked-list will quickly look like garbage.
    Teacher: "You connect with Internet Explorer, but what is your browser? You know, Yahoo, Webcrawler...?" It's great to see the educational system moving in the right direction

  7. #7
    Registered User
    Join Date
    Mar 2006
    Posts
    725
    Your sort algorithm is a little retarded. Read http://en.wikipedia.org/wiki/Sorting_algorithm for real sorting algorithms which do work. In any case, you probably want to do two passes in swap(), one going down the list and one back up, so small strings at the end can be swapped to the front as expected. You should really try out your algorithms on paper (with example strings) to see what-in-carnation are wrong with them before you actually write code. If you want a permanently sorted structure, it might also be more logical (and probably faster) to use a self-balancing binary tree for the job.
    Code:
    #include <stdio.h>
    
    void J(char*a){int f,i=0,c='1';for(;a[i]!='0';++i)if(i==81){
    puts(a);return;}for(;c<='9';++c){for(f=0;f<9;++f)if(a[i-i%27+i%9
    /3*3+f/3*9+f%3]==c||a[i%9+f*9]==c||a[i-i%9+f]==c)goto e;a[i]=c;J(a);a[i]
    ='0';e:;}}int main(int c,char**v){int t=0;if(c>1){for(;v[1][
    t];++t);if(t==81){J(v[1]);return 0;}}puts("sudoku [0-9]{81}");return 1;}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorting linked list please help with CODE
    By scarlet00014 in forum C Programming
    Replies: 3
    Last Post: 09-27-2008, 11:24 PM
  2. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  3. How to use Linked List?
    By MKashlev in forum C++ Programming
    Replies: 4
    Last Post: 08-06-2002, 07:11 AM
  4. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM