题解 | #反转链表#

反转链表

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 * };
 */

#include <stdlib.h>
// void insert(struct ListNode** link,struct ListNode** temp){
//     if((*link)==NULL){
//         (*link)=(*temp);
//     }
//     else{
//         (*temp)->next =(*link);
//         (*link)=(*temp);
//     }

// }

// struct ListNode* ReverseList(struct ListNode* pHead ) {
//     // write code here
//     struct ListNode* new =NULL;

//     while (pHead) {
//         struct ListNode* temp = (struct ListNode*)malloc(sizeof(struct ListNode));
//         temp->val=pHead->val;
//         temp->next =NULL;
//         insert(&new,&temp);
//     }
//     return new;

// }

struct ListNode* ReverseList(struct ListNode* pHead) {
    struct  ListNode* pre = NULL;
    struct  ListNode* cur = pHead;
    struct ListNode* nex = NULL; // 这里可以指向NUll,循环里面要重新指向
    while (cur) {
        nex = cur->next;
        cur->next = pre;
        pre = cur;
        cur = nex;
    }
    return pre;
}

法1:遍历链表,同时利用头插法建立一个新链表,最后返回新链表即可;但空间复杂度为O(n),不符合题意;

法2:三指针法, nex = cur->next; cur->next = pre; pre = cur; cur = nex;,遍历一遍即可,空间空间复杂度为O(1)

全部评论

相关推荐

04-01 12:25
中南大学 Java
枯基Evan_:腾讯一面写过11次的题目没写出来
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务