Reverse Linked List
题目:链接
代码1:/**
* 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)
return head;
ListNode * curr = head->next;
head->next = nullptr;
while(curr)
{
ListNode *temp = curr->next;
curr->next = head;
head = curr;
curr = temp;
}
return head;
}
};
/**
* 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* newhead = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return newhead;
}
};