AlenaNuna

导航

反转链表

要求空间复杂度 O(1) ,时间复杂度 O(n) 。

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=295&tqId=23286&ru=/exam/company&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Fcompany%3FcurrentTab%3Drecommand%26jobId%3D100%26selectStatus%3D0%26tagIds%3D239

核心代码模式都不会用,我就彻底老实了

 1 /**
 2  * struct ListNode {
 3  *    int val;
 4  *    struct ListNode *next;
 5  *    ListNode(int x) : val(x), next(nullptr) {}
 6  * };
 7  */
 8 class Solution {
 9 public:
10     /**
11      * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
12      *
13      * 
14      * @param p ListNode类 
15      * @return ListNode类
16      */
17     ListNode* ReverseList(ListNode* p) {
18         // write code here
19         ListNode* pre=nullptr;
20         while(p){
21             ListNode* t=p->next;
22             p->next=pre;
23             pre=p;
24             p=t;
25         }
26         return pre;
27     }
28 };

 

posted on 2024-09-01 01:00  AlenaNuna  阅读(15)  评论(0)    收藏  举报