菜鸟刷力扣 6

反转链表

在这里插入图片描述思路:很简单的题目,开始以为要先遍历到最后一个,然后记前一个点的地址,再修改;及第一次遍历找到 5 和4 的地址,然后5->next=4;第二次找到4 3,4->next=3;但是这样很傻。
第二种 map 记录第几个数和地址 5->next=map.find(第4个的val值)
第三种 ,突然灵感来了,记录第一个值 first 记录之后的值 second;
while(second!=nullptr)
一定要先定义一个temp记录second->next,因为等会要反转链表了,反转之后的second->next就不是原来的那个后面的元素地址了;
temp=second->next;
second->next=first;
first=second;
second=temp;

代码如下:`

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
             //判断是否为空节点
             if(head==nullptr)  return head;
             //判断是否只有一个节点
              if(head->next==nullptr)  return head;
            //如果是两节点以上
             ListNode* first,* second;
             ListNode* temp=nullptr;
             //记录当前节点与下一个节点
             first=head;
             second=first->next;
             first->next=nullptr;  
             while(second!=nullptr)
             {
                 temp=second->next;
                 second->next=first;
                 first=second;
                 second=temp;
             }

            return first;
             
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值