不会。
递归。有点慢,18ms。
/** * 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==NULL||head->next==NULL){ return head; } ListNode * p=reverseList(head->next); head->next->next=head; head->next=NULL; return p; } };
来源:https://blog.csdn.net/geekmanong/article/details/51097196
ListNode* reverseList(ListNode* head) { ListNode* newHead = NULL; while (head) { ListNode* nextNode = head->next; head->next = newHead; newHead = head; head = nextNode; } return newHead; }
9ms,来自:https://blog.csdn.net/NoMasp/article/details/50514593
快了一倍?
class Solution { public: ListNode* reverseList(ListNode* head) { if (head == nullptr) { return nullptr; } ListNode *pre = nullptr, *next = nullptr; while (head != nullptr) { next = head->next; head->next = pre; pre = head; head = next; } return pre; } };
最快的。7ms?
原文地址:https://www.cnblogs.com/azureice/p/leetcode206.html
时间: 2024-10-31 12:47:47