Solution 1. Iterative method
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* node = head;
while(node){
head = node;
node = node->next;
head->next = prev;
prev = head;
}
return head;
}
Solution 2. Recursion
ListNode* reverseList(ListNode* head) {
if(!head || !head->next) return head;
ListNode* node = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return node;
}
Solution 2. With the help of a stack
ListNode* reverseList(ListNode* head) {
stack<ListNode*> st;
ListNode* node = head;
while(node){
st.push(node);
node = node->next;
}
if(head) {
head = st.top();
node = head;
st.pop();
}
while(!st.empty()) {
node->next = st.top();
st.pop();
node = node->next;
}
if(node) node->next = nullptr;
return head;
}
No comments:
Post a Comment