https://leetcode.com/problems/reverse-linked-list/#/solutions
题目很简单就是“反转”链表:
我的解法思路很简单,将所有节点的next指针指向前一个节点就可以了
/**
* 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;
}
};
网友评论