题目
反转一个单链表。
示例
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
思路
思路一(迭代)
思路二(递归)
代码
代码一(迭代)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = nullptr;
ListNode* cur = head;
while ( cur ) {
ListNode* temp = cur;
cur = cur->next;
temp->next = pre;
pre = temp;
}
return pre;
}
};
代码二(递归)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if ( head == nullptr || head->next == nullptr )
return head;
ListNode* p = reverseList( head->next );
head->next->next = head;
head->next = nullptr;
return p;
}
};