Thread: sortedLinkedList

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    46

    sortedLinkedList

    Hi everyone,I'm trying to write a piece of code that sort the number through linked list.For example when the user gives 4,3,10,2,1
    output should be like this 10 4 3 2 1 but I've seg fault and i dont know what should i do and where i am wrong.Is there anyone who can help me ? thanks a lot.

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    struct node{
    	int deger/*value*/;
    	struct node * next;
    };
    
    
    int data;
    struct node * bas=NULL;
    
    
    struct node * fonk_mknode(int data){
    
    
    	struct node * np;	
    	np=malloc(sizeof(struct node));	
    	np->deger=data;
    	np->next=NULL;
    	return np;	
    }
    
    
    struct node * fonk_insert(struct node ** bas,int data){
    	struct node *tutar;
    	struct node *gezici=*bas;
    	struct node *bilinmez=NULL;
    	
    	tutar=fonk_mknode(data);
    	
    	if(*bas==NULL){
    		*bas=tutar;
    		
    		}
    	
    	else{
    		
    		while(gezici->deger>(tutar->deger)){
    			if(gezici->next==NULL){
    				gezici->next=tutar;}
    			
    			bilinmez=gezici;
    			gezici=gezici->next;
    			
    		}
    		bilinmez->next=tutar;
    		tutar->next=gezici;
    		
    	}
    
    
    return *bas;
    }
    
    
    void fonk_print(struct node *list){
    
    
    	for( ;list;list=list->next)
    		printf("%d ",list->deger);
    	printf("\n");
    }
    
    
    int main(){	
    	while(1){
    		scanf("%d",&data);
    		if(data==-1)
    		break;
    		fonk_insert(&bas,data);
    	}
    fonk_print(bas);
    return 0;
    }

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    What happens when your while loop is false; the first time though.

    Code:
    while(gezici->deger>(tutar->deger)){
    At this line
    Code:
    bilinmez->next=tutar;
    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  3. #3
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    I find your code a little difficult to follow because IT'S IN ANOTHER FREAKING LANGUAGE! Since this is an English site, it would be best for you to post your code in English, if possible.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

Popular pages Recent additions subscribe to a feed