1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Reverse a linked list

Discussion in 'C' started by Me@earth, Jun 24, 2008.

  1. Me@earth

    Me@earth New Member

    Joined:
    May 22, 2008
    Messages:
    11
    Likes Received:
    0
    Trophy Points:
    0
    Can anyone help me with a code to reverse a linked list
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,285
    Likes Received:
    364
    Trophy Points:
    83
  3. aali

    aali New Member

    Joined:
    Jul 16, 2008
    Messages:
    18
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    student
    Location:
    Riyadh
    Code:
    void SinglyLinkedList::reverse()
    	{
    		/********************
    		Node* currentFirst;
    		Node* currentLast;
    		 currentFirst=first_ptr;
    		***********************
    		if(first_ptr==NULL||first_ptr->next==NULL)
    			return;
    		
    		Node*current=first_ptr->next;
    		Node *pervious=first_ptr;
    		Node*after;
    		first_ptr->next=NULL;
    		while(current!=NULL)
    			{
    			after=current->next;
    			current->next=pervious;
    			pervious=current;
    			current=after;
    
    			}
    		first_ptr=pervious;
    		*********************/
    	/**********other way**********/
    	if(first_ptr==NULL||first_ptr->next==NULL)
    			return;
    		
    		Node*current=first_ptr->next;
    		//Node *pervious=first_ptr;
    		Node*newNode=NULL;
    		first_ptr->next=NULL;
    		while(current!=NULL)
    			{
    			newNode=current->next;
    			current->next=first_ptr;
    			first_ptr=current;
    			current=newNode;
    
    			}
    		//first_ptr=pervious;
        
    	/*********************************/
    	
    	}
     
    Last edited by a moderator: Jul 22, 2008

Share This Page