Reverse a singly linked list.
反转一个单链表。
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
①迭代法图解:
①C++(迭代法)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = nullptr;
ListNode* cur = head;
while(cur!=nullptr){
ListNode* tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
};
②递归法图解:
②C++(递归法)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==nullptr || head->next==nullptr) {
return head;
}
ListNode* cur = reverseList(head->next);
head->next->next = head;
//防止链表循环,需要将head.next设置为空
head->next = nullptr;
//每层递归函数都返回cur,也就是最后一个节点
return cur;
}
};