Find the answer to your Linux question:
Results 1 to 2 of 2
Hi, Pasted below is my procedure(SortList) to sort the singly link list,but this is not working. i might be doing something stupid,and i would really apprecieate if you guys can ...
  1. #1
    Just Joined! amit4g's Avatar
    Join Date
    Feb 2007
    Location
    Bangalore,India
    Posts
    63

    link-list sorting

    Hi,

    Pasted below is my procedure(SortList) to sort the singly link list,but this is not working.
    i might be doing something stupid,and i would really apprecieate if you guys
    can let me realise the mistake in my code(a silly code with no importance)

    4 struct node{
    5 int data;
    6 struct node *next;
    7 };

    29 /* returns the length of the link list*/
    30 int Length(struct node* head){
    31 struct node *current = head;
    32 int count = 0;
    33 while(current != NULL){
    34 count++;
    35 current = current->next;
    36 }
    37 return(count);
    38 }

    40 /* prints the data field of the each node*/
    41 void LinkTraverse(struct node* head){
    42 struct node* current = head;
    43 int i = 1;
    44 while(current != NULL){
    45 printf("element %d is %d\n",i,current->data);
    46 i++;
    47 current = current->next;
    48 }
    49 }


    140 /*sort the link*/
    141 void SortList(struct node** headRef){
    142 struct node* current = *headRef;
    143 int i,j,temp,length;
    144 length = Length(current);
    145 for(i = length;i >= 1 ; i--){
    146 for(j = 1; j <= i; j++){
    147 if(current->data > current->next->data){
    148 temp = current->data;
    149 current->data = current->next->data;
    150 current->next->data = temp;
    151 }
    152 }
    153 }
    154 LinkTraverse(head);
    155 }

    ~amit

  2. #2
    Just Joined! amit4g's Avatar
    Join Date
    Feb 2007
    Location
    Bangalore,India
    Posts
    63
    After making the following changes in the "SortList" procedure,it is working

    /*sort the link*/
    void SortList(struct node** headRef){
    struct node* current = *headRef;
    int i,j,temp,length;
    length = Length(current);
    printf("length = %d\n",length);
    for(i = length;i > 1 ; i--){
    current = *headRef;
    for(j = 1; j < i; j++){
    register struct node* n = current->next;
    if(current->data > n->data){
    temp = current->data;
    current->data = n->data;
    n->data = temp;
    }
    current = n;
    }
    }
    }


    ~amit

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...