当前位置:网站首页>【剑指Offer】面试题24.反转链表
【剑指Offer】面试题24.反转链表
2022-06-13 04:16:00 【LuZhouShiLi】
面试题24.反转链表
题目
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
思路
定义三个指针,pre,cur,temp;当我需要调整节点cur的next指针时,除了需要知道节点i本身,还需要知道它的前一个节点h,将节点i的next指针指向节点h,同时我们还需要保存节点i的下一个节点J,为了防止链表断开。当我们将节点i的next指向前一个节点h的时候,此时将Pre指针指向i,cur指针指向节点temp;
代码
/** * 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 *current = head,*pre = nullptr;
while(current != nullptr)
{
ListNode *tmp = current->next;//存储下一个节点
current->next = pre;// 将当前节点的next指向前一个节点
// 修改之后 当前节点变成pre
pre = current; // pre暂存当前节点
current = tmp; // 当前指针指向临时节点
}
return pre;
}
};
边栏推荐
- 史上最详细的Swin-Transformer 掩码机制(mask of window attentation)————shaoshuai
- Knife4j aggregation 2.0.9 supports automatic refresh of routing documents
- Lambda end operation find and match findfirst
- Example of try catch finally execution sequence
- Interpretation of usb-if bc1.2 charging protocol
- Milliards de données pour déterminer si un élément existe
- Line height equals height why not center
- 十億數據量 判斷元素是否存在
- 出现Could not find com.scwang.smart:refresh-layout-kernel:2.0.3.Required by: project :app 无法加载第三方包情况
- Billions of data to determine whether the element exists
猜你喜欢
Advanced Mathematics (Seventh Edition) Tongji University exercises 1-3 personal solutions
[test development] automated test selenium (II) -- common APIs for webdriver
[note]vs2015 compilation of masm32 using MASM32 Library
Interpretation of usb-if bc1.2 charging protocol
5G China unicom AP:B SMS ASCII 转码要求
Introduction to MCU peripherals: temperature sensor DS18B20
Unity Shader 学习 004-Shader 调试 平台差异性 第三方调试工具
[web] cookies and sessions
Goframe day 4
Redis数据持久化
随机推荐
出现Could not find com.scwang.smart:refresh-layout-kernel:2.0.3.Required by: project :app 无法加载第三方包情况
SCM: introduction to Modbus communication protocol
Single chip microcomputer: d/a output
Summary of webdriver API for web automated testing
缓存读写--写
Data analysis report
[test development] file compression project practice
MCU: RS485 communication and Modbus Protocol
[test development] basic concepts related to testing
Configuration and practice of shardingsphere JDBC sub database separation of read and write
Call C function in Lua
Big Five personality learning records
Single chip microcomputer: infrared remote control communication principle
Precautions for stream flow
ET框架-22 创建ServerInfo实体及事件
电磁兼容常用名词术语
MCU: EEPROM multi byte read / write operation sequence
Milliards de données pour déterminer si un élément existe
Answer private message @ Tiantian Wx //2022-6-12 C language 51 single chip microcomputer led analog traffic light
ROS中的msg消息