This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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; | |
} |
No comments:
Post a Comment