Thursday, January 20, 2011

Reverse a Linked List using recursion

Input: 1->2->3->4->5->6->7->8->NULL
Output: 8->7->6->5->4->3->2->1->NULL

// take head pointer and return new head pointer
void reverse(NODE *head) {

    NODE *cur, *prev = NULL, *temp = NULL;
    
    if( head == NULL )
        return null; 
        
    cur = head; 
    
    while( cur ){        
    
        if( cur->next == null ) {
            cur->next = prev;
            return cur;
        }
            
        temp = cur->next;
        cur->next = prev;
        prev = cur;
        cur = temp;
    }    
} 

int main(){
  NODE *head = /* linked list */;
  NODE *reverse_list = reverse(head);
}

No comments :

Post a Comment