Leetcode | 206 Reverse Linked List

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;       
    }
};


代码2:
/**
 * 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;   
    }
};


猜你喜欢

转载自blog.csdn.net/isunbin/article/details/81036809