Thread: can figure out what this function does..

  1. #1
    Banned
    Join Date
    Oct 2008
    Posts
    1,535

    can figure out what this function does..

    its so complicated
    i cant see the general way
    Code:
    Node* what2(Node *head){
    	Node *temp, *prev, *next, *prevmax, *newhead;	
    	while(head->next){
    		prevmax = prev = next = NULL;
    		for(temp=head; temp; temp=temp->next){
    			printf("%d ", temp->value);
    			next = temp -> next;
    			if((!prev || prev->value < temp->value) && 
    (!next || temp->value > next->value)){
    				if(! prevmax )
    					newhead = temp;
    				else
    					prevmax->next= temp;
    				prevmax = temp;
    			}
    			if(prev && prev!=prevmax)
    				free(prev);
    			prev = temp;
    		}
    		prevmax -> next = NULL;
    		head = newhead;
    		putchar('\n');
    	}
    	return head;
    }

  2. #2
    int x = *((int *) NULL); Cactus_Hugger's Avatar
    Join Date
    Jul 2003
    Location
    Banks of the River Styx
    Posts
    902
    It would appear to find the largest element in a singly-linked-link, and free the entire list except for that element. I would also add that this code smells, and I can't tell you for certain that it is bug free/works. If it does indeed free everything but the largest element, then I would have written it:
    Code:
    Node *reduce(Node *head)
    {
    	Node *largest = NULL, *i, *temp;
    	
    	// Find the max
    	for(i = head; i; i->next)
    	{
    		largest = (largest && largest->value > i->value ? largest : i);
    	}
    	
    	// Free everything but the max
    	for(i = head; i;)
    	{
    		temp = i;
    		i = i->next;
    		if(temp != largest)
    		{
    			free(temp);
    		}
    	}
    	
    	return largest;
    }
    About 15 lines less, much easier to read, and I can even tell you that it runs in O(N).
    long time; /* know C? */
    Unprecedented performance: Nothing ever ran this slow before.
    Any sufficiently advanced bug is indistinguishable from a feature.
    Real Programmers confuse Halloween and Christmas, because dec 25 == oct 31.
    The best way to accelerate an IBM is at 9.8 m/s/s.
    recursion (re - cur' - zhun) n. 1. (see recursion)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  2. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  3. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  4. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  5. Including lib in a lib
    By bibiteinfo in forum C++ Programming
    Replies: 0
    Last Post: 02-07-2006, 02:28 PM