Thursday, April 24, 2014

Reverse A Singly Linked List

//Recursive method to reverse
Node* reverse(Node* cur, Node* pre){
if(cur->next == NULL){//end of the list
cur->next = pre;
return cur;
}
else{
Node* temp = reverse(cur->next, cur);
cur->next = pre;
return temp;
}
}
reverse(head, NULL);
//Iterative method
Node* reverse(Node* cur){
Node* pre=NULL, temp=NULL;
while(cur){
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
view raw gistfile1.cpp hosted with ❤ by GitHub

No comments:

Post a Comment