https://leetcode.com/problems/reverse-linked-list/#/solutions
題目很簡(jiǎn)單就是“反轉(zhuǎn)”鏈表:
我的解法思路很簡(jiǎn)單,將所有節(jié)點(diǎn)的next指針指向前一個(gè)節(jié)點(diǎn)就可以了
/**
* 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* next = NULL;
ListNode* pre = NULL;
if(head == NULL){
return NULL;
}
while(head != NULL){
next = head->next;
head->next = pre;
pre = head;
head = next;
}
return pre;
}
};
但這題還有一種巧妙的做法就是利用遞歸
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !(head -> next)) return head;
ListNode* node = reverseList(head -> next);
head -> next -> next = head;
head -> next = NULL;
return node;
}
};