Leetcode刷题笔记206反转链表

第一次超出时间限制

/**
 * 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* pNew = head->next;
        ListNode* pHead = head;
        ListNode* pTemp = pNew->next;
        while(pNew != NULL)
        {
            pHead->next = pNew->next;
            pNew->next = head;
            head = pNew;
            pNew = pTemp;
            if(pTemp->next != NULL){
                pTemp = pTemp->next;
            }
        }
        return head;
    }
};

8ms通过结果

/**
 * 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* new_head = NULL;
        ListNode* next = NULL;
        while(head){
            next = head->next;
            head->next = new_head;
            new_head = head;
            head = next;
        }
        return new_head;
    }
}; 

你可能感兴趣的:(leetcode算法刷题,leetcode算法刷题)