题目
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
思路
1.链表的问题注意画出草稿图,理清楚指针的操作步骤就可以了
2.递归程序最重要的是专注于input,output,func,不用管递归的函数是怎样做的。
实现
迭代
/**
* 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* current = nullptr;
if (!head) {
return nullptr;
}
current = head;
while (current) {
ListNode* next = current->next;
current->next = pre;
pre = current;
current = next;
}
return pre;
}
};
递归
class Solution {
public:
ListNode* reverseList(ListNode* head) {
return reverseList(nullptr, head);
}
ListNode* reverseList(ListNode* pre, ListNode* head) {
if (!head) {
return pre;
}
//每次反转一次
ListNode* tmp = head->next;
head->next = pre;
return reverseList(head, tmp);
}
};