算法刷题-双指针-反转链表

2023-11-11

反转链表的写法很简单,一些同学甚至可以背下来但过一阵就忘了该咋写,主要是因为没有理解真正的反转过程。

206.反转链表

力扣题目链接

题意:反转一个单链表。

示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

思路

如果再定义一个新的链表,实现链表元素的反转,其实这是对内存空间的浪费。

其实只需要改变链表的next指针的指向,直接将链表反转 ,而不用重新定义一个新的链表,如图所示:

206_反转链表

之前链表的头节点是元素1, 反转之后头结点就是元素5 ,这里并没有添加或者删除节点,仅仅是改变next指针的方向。

那么接下来看一看是如何反转的呢?

我们拿有示例中的链表来举例,如动画所示:(纠正:动画应该是先移动pre,在移动cur)

在这里插入图片描述

首先定义一个cur指针,指向头结点,再定义一个pre指针,初始化为null。

然后就要开始反转了,首先要把 cur->next 节点用tmp指针保存一下,也就是保存一下这个节点。

为什么要保存一下这个节点呢,因为接下来要改变 cur->next 的指向了,将cur->next 指向pre ,此时已经反转了第一个节点了。

接下来,就是循环走如下代码逻辑了,继续移动pre和cur指针。

最后,cur 指针已经指向了null,循环结束,链表也反转完毕了。 此时我们return pre指针就可以了,pre指针就指向了新的头结点。

C++代码

双指针法

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* temp; // 保存cur的下一个节点
        ListNode* cur = head;
        ListNode* pre = NULL;
        while(cur) {
            temp = cur->next;  // 保存一下 cur的下一个节点,因为接下来要改变cur->next
            cur->next = pre; // 翻转操作
            // 更新pre 和 cur指针
            pre = cur;
            cur = temp;
        }
        return pre;
    }
};

递归法

递归法相对抽象一些,但是其实和双指针法是一样的逻辑,同样是当cur为空的时候循环结束,不断将cur指向pre的过程。

关键是初始化的地方,可能有的同学会不理解, 可以看到双指针法中初始化 cur = head,pre = NULL,在递归法中可以从如下代码看出初始化的逻辑也是一样的,只不过写法变了。

具体可以看代码(已经详细注释),双指针法写出来之后,理解如下递归写法就不难了,代码逻辑都是一样的。

class Solution {
public:
    ListNode* reverse(ListNode* pre,ListNode* cur){
        if(cur == NULL) return pre;
        ListNode* temp = cur->next;
        cur->next = pre;
        // 可以和双指针法的代码进行对比,如下递归的写法,其实就是做了这两步
        // pre = cur;
        // cur = temp;
        return reverse(cur,temp);
    }
    ListNode* reverseList(ListNode* head) {
        // 和双指针法初始化是一样的逻辑
        // ListNode* cur = head;
        // ListNode* pre = NULL;
        return reverse(NULL, head);
    }

};

我们可以发现,上面的递归写法和双指针法实质上都是从前往后翻转指针指向,其实还有另外一种与双指针法不同思路的递归写法:从后往前翻转指针指向。

具体代码如下(带详细注释):

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        // 边缘条件判断
        if(head == NULL) return NULL;
        if (head->next == NULL) return head;
        
        // 递归调用,翻转第二个节点开始往后的链表
        ListNode *last = reverseList(head->next);
        // 翻转头节点与第二个节点的指向
        head->next->next = head;
        // 此时的 head 节点为尾节点,next 需要指向 NULL
        head->next = NULL;
        return last;
    }
}; 

其他语言版本

Java:

// 双指针
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode cur = head;
        ListNode temp = null;
        while (cur != null) {
            temp = cur.next;// 保存下一个节点
            cur.next = prev;
            prev = cur;
            cur = temp;
        }
        return prev;
    }
}
// 递归 
class Solution {
    public ListNode reverseList(ListNode head) {
        return reverse(null, head);
    }

    private ListNode reverse(ListNode prev, ListNode cur) {
        if (cur == null) {
            return prev;
        }
        ListNode temp = null;
        temp = cur.next;// 先保存下一个节点
        cur.next = prev;// 反转
        // 更新prev、cur位置
        // prev = cur;
        // cur = temp;
        return reverse(cur, temp);
    }
}
// 从后向前递归
class Solution {
    ListNode reverseList(ListNode head) {
        // 边缘条件判断
        if(head == null) return null;
        if (head.next == null) return head;
        
        // 递归调用,翻转第二个节点开始往后的链表
        ListNode last = reverseList(head.next);
        // 翻转头节点与第二个节点的指向
        head.next.next = head;
        // 此时的 head 节点为尾节点,next 需要指向 NULL
        head.next = null;
        return last;
    } 
}

Python迭代法:

#双指针
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        cur = head   
        pre = None
        while(cur!=None):
            temp = cur.next # 保存一下 cur的下一个节点,因为接下来要改变cur->next
            cur.next = pre #反转
            #更新pre、cur指针
            pre = cur
            cur = temp
        return pre

Python递归法:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        
        def reverse(pre,cur):
            if not cur:
                return pre
                
            tmp = cur.next
            cur.next = pre

            return reverse(cur,tmp)
        
        return reverse(None,head)

Python递归法从后向前:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head or not head.next: return head
        p = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return p

Go:

//双指针
func reverseList(head *ListNode) *ListNode {
    var pre *ListNode
    cur := head
    for cur != nil {
        next := cur.Next
        cur.Next = pre
        pre = cur
        cur = next
    }
    return pre
}

//递归
func reverseList(head *ListNode) *ListNode {
    return help(nil, head)
}

func help(pre, head *ListNode)*ListNode{
    if head == nil {
        return pre
    }
    next := head.Next
    head.Next = pre
    return help(head, next)
}

javaScript:

/**
 * @param {ListNode} head
 * @return {ListNode}
 */

// 双指针:
var reverseList = function(head) {
    if(!head || !head.next) return head;
    let temp = null, pre = null, cur = head;
    while(cur) {
        temp = cur.next;
        cur.next = pre;
        pre = cur;
        cur = temp;
    }
    // temp = cur = null;
    return pre;
};

// 递归:
var reverse = function(pre, head) {
    if(!head) return pre;
    const temp = head.next;
    head.next = pre;
    pre = head
    return reverse(pre, temp);
}

var reverseList = function(head) {
    return reverse(null, head);
};

// 递归2
var reverse = function(head) {
    if(!head || !head.next) return head;
    // 从后往前翻
    const pre = reverse(head.next);
    head.next = pre.next;
    pre.next = head;
    return head;
}

var reverseList = function(head) {
    let cur = head;
    while(cur && cur.next) {
        cur = cur.next;
    }
    reverse(head);
    return cur;
};

TypeScript:

// 双指针法
function reverseList(head: ListNode | null): ListNode | null {
    let preNode: ListNode | null = null,
        curNode: ListNode | null = head,
        tempNode: ListNode | null;
    while (curNode) {
        tempNode = curNode.next;
        curNode.next = preNode;
        preNode = curNode;
        curNode = tempNode;
    }
    return preNode;
};

// 递归(从前往后翻转)
function reverseList(head: ListNode | null): ListNode | null {
    function recur(preNode: ListNode | null, curNode: ListNode | null): ListNode | null {
        if (curNode === null) return preNode;
        let tempNode: ListNode | null = curNode.next;
        curNode.next = preNode;
        preNode = curNode;
        curNode = tempNode;
        return recur(preNode, curNode);
    }
    return recur(null, head);
};

// 递归(从后往前翻转)
function reverseList(head: ListNode | null): ListNode | null {
    if (head === null) return null;
    let newHead: ListNode | null;
    function recur(node: ListNode | null, preNode: ListNode | null): void {
        if (node.next === null) {
            newHead = node;
            newHead.next = preNode;
        } else {
            recur(node.next, node);
            node.next = preNode;
        }
    }
    recur(head, null);
    return newHead;
};

Ruby:

# 双指针
# Definition for singly-linked list.
# class ListNode
#     attr_accessor :val, :next
#     def initialize(val = 0, _next = nil)
#         @val = val
#         @next = _next
#     end
# end
def reverse_list(head)
  # return nil if head.nil?	# 循环判断条件亦能起到相同作用因此不必单独判断
  cur, per = head, nil
  until cur.nil?
    tem = cur.next
    cur.next = per
    per = cur
    cur = tem
  end
  per
end

# 递归
# Definition for singly-linked list.
# class ListNode
#     attr_accessor :val, :next
#     def initialize(val = 0, _next = nil)
#         @val = val
#         @next = _next
#     end
# end
def reverse_list(head)
  reverse(nil, head)
end

def reverse(pre, cur)
  return pre if cur.nil?
  tem = cur.next
  cur.next = pre
  reverse(cur, tem)	# 通过递归实现双指针法中的更新操作
end

Kotlin:

fun reverseList(head: ListNode?): ListNode? {
    var pre: ListNode? = null
    var cur = head
    while (cur != null) {
        val temp = cur.next
        cur.next = pre
        pre = cur
        cur = temp
    }
    return pre
}
/**
 * Example:
 * var li = ListNode(5)
 * var v = li.`val`
 * Definition for singly-linked list.
 * class ListNode(var `val`: Int) {
 *     var next: ListNode? = null
 * }
 */
class Solution {
    fun reverseList(head: ListNode?): ListNode? {
        // temp用来存储临时的节点
        var temp: ListNode?
        // cur用来遍历链表
        var cur: ListNode? = head
        // pre用来作为链表反转的工具
        // pre是比pre前一位的节点
        var pre: ListNode? = null
        while (cur != null) {
            // 临时存储原本cur的下一个节点
            temp = cur.next
            // 使cur下一节点地址为它之前的
            cur.next = pre
            // 之后随着cur的遍历移动pre
            pre = cur;
            // 移动cur遍历链表各个节点
            cur = temp;
        }
        // 由于开头使用pre为null,所以cur等于链表本身长度+1,
        // 此时pre在cur前一位,所以此时pre为头节点
        return pre;
    }
}

Swift:

/// 双指针法 (迭代)
/// - Parameter head: 头结点
/// - Returns: 翻转后的链表头结点
func reverseList(_ head: ListNode?) -> ListNode? {
    if head == nil || head?.next == nil {
        return head
    }
    var pre: ListNode? = nil
    var cur: ListNode? = head
    var temp: ListNode? = nil
    while cur != nil {
        temp = cur?.next
        cur?.next = pre
        pre = cur
        cur = temp
    }
    return pre
}

/// 递归
/// - Parameter head: 头结点
/// - Returns: 翻转后的链表头结点
func reverseList2(_ head: ListNode?) -> ListNode? {
    return reverse(pre: nil, cur: head)
}
func reverse(pre: ListNode?, cur: ListNode?) -> ListNode? {
    if cur == nil {
        return pre
    }
    let temp: ListNode? = cur?.next
    cur?.next = pre
    return reverse(pre: cur, cur: temp)
}

C:
双指针法:

struct ListNode* reverseList(struct ListNode* head){
    //保存cur的下一个结点
    struct ListNode* temp;
    //pre指针指向前一个当前结点的前一个结点
    struct ListNode* pre = NULL;
    //用head代替cur,也可以再定义一个cur结点指向head。
    while(head) {
        //保存下一个结点的位置
        temp = head->next;
        //翻转操作
        head->next = pre;
        //更新结点
        pre = head;
        head = temp;
    }
    return pre;
}

递归法:

struct ListNode* reverse(struct ListNode* pre, struct ListNode* cur) {
    if(!cur)
        return pre;
    struct ListNode* temp = cur->next;
    cur->next = pre;
    //将cur作为pre传入下一层
    //将temp作为cur传入下一层,改变其指针指向当前cur
    return reverse(cur, temp);
}

struct ListNode* reverseList(struct ListNode* head){
    return reverse(NULL, head);
}

PHP:

// 双指针法:
function reverseList($head) {
    $cur = $head;
    $pre = NULL;
    while($cur){
        $temp = $cur->next; 
        $cur->next = $pre;
        $pre = $cur;
        $cur = $temp;
    }
    return $pre;
    }

Scala:
双指针法:

object Solution {
  def reverseList(head: ListNode): ListNode = {
    var pre: ListNode = null
    var cur = head
    while (cur != null) {
      var tmp = cur.next
      cur.next = pre
      pre = cur
      cur = tmp
    }
    pre
  }
}

递归法:

object Solution {
  def reverseList(head: ListNode): ListNode = {
    reverse(null, head)
  }

  def reverse(pre: ListNode, cur: ListNode): ListNode = {
    if (cur == null) {
      return pre    // 如果当前cur为空,则返回pre
    }
    val tmp: ListNode = cur.next
    cur.next = pre
    reverse(cur, tmp)   // 此时cur成为前一个节点,tmp是当前节点
  }

}

Rust:
双指针法:

impl Solution {
    pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        let mut cur = head;
        let mut pre = None;
        while let Some(mut node) = cur.take() {
            cur = node.next;
            node.next = pre;
            pre = Some(node);
        }
        pre
    }
}

递归法:

impl Solution {
    pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        fn rev(
            mut head: Option<Box<ListNode>>,
            mut pre: Option<Box<ListNode>>,
        ) -> Option<Box<ListNode>> {
            if let Some(mut node) = head.take() {
                let cur = node.next;
                node.next = pre;
                pre = Some(node);
                return rev(cur, pre);
            }
            pre
        }
        rev(head, None)
    }
}

C#:
三指针法, 感觉会更直观:

public LinkNumbers Reverse()
{
    ///用三指针,写的过程中能够弥补二指针在翻转过程中的想象
    LinkNumbers pre = null;
    var move = root;
    var next = root;

    while (next != null)
    {
        next = next.linknext;
        move.linknext = pre;
        pre = move;
        move = next;
    }
    root = pre;
    return root;
}

///LinkNumbers的定义
public class LinkNumbers
{
    /// <summary>
    /// 链表值
    /// </summary>
    public int value { get; set; }

    /// <summary>
    /// 链表指针
    /// </summary>
    public LinkNumbers linknext { get; set; }
}

使用虚拟头结点解决链表翻转

使用虚拟头结点,通过头插法实现链表的翻转(不需要栈)

// 迭代方法:增加虚头结点,使用头插法实现链表翻转
public static ListNode reverseList1(ListNode head) {
    // 创建虚头结点
    ListNode dumpyHead = new ListNode(-1);
    dumpyHead.next = null;
    // 遍历所有节点
    ListNode cur = head;
    while(cur != null){
        ListNode temp = cur.next;
        // 头插法
        cur.next = dumpyHead.next;
        dumpyHead.next = cur;
        cur = temp;
    }
    return dumpyHead.next;
}

使用栈解决反转链表的问题

  • 首先将所有的结点入栈
  • 然后创建一个虚拟虚拟头结点,让cur指向虚拟头结点。然后开始循环出栈,每出来一个元素,就把它加入到以虚拟头结点为头结点的链表当中,最后返回即可。
public ListNode reverseList(ListNode head) {
    // 如果链表为空,则返回空
    if (head == null) return null;
    // 如果链表中只有只有一个元素,则直接返回
    if (head.next == null) return head;
    // 创建栈 每一个结点都入栈
    Stack<ListNode> stack = new Stack<>();
    ListNode cur = head;
    while (cur != null) {
        stack.push(cur);
        cur = cur.next;
    }
    // 创建一个虚拟头结点
    ListNode pHead = new ListNode(0);
    cur = pHead;
    while (!stack.isEmpty()) {
        ListNode node = stack.pop();
        cur.next = node;
        cur = cur.next;
    }
    // 最后一个元素的next要赋值为空
    cur.next = null;
    return pHead.next;
}

采用这种方法需要注意一点。就是当整个出栈循环结束以后,cur正好指向原来链表的第一个结点,而此时结点1中的next指向的是结点2,因此最后还需要cur.next = null
image-20230117195418626

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

算法刷题-双指针-反转链表 的相关文章

随机推荐

  • python-sqlalchemy中设置autocommit

    这个只需要在连接数据库的时候加上即可 SQLALCHEMY DATABASE URI mysql pymysql username passwrod ip prot database charset utf8 autocommit true
  • Linux查看日志命令,压缩日志不解压直接查看

    日常工作中经常要在linux服务器上查看日志定位问题 本文简单总结下常用查看日志的命令 监控日志命令 tail f file log tailf file log 上一个命令的快捷键 但是有些系统默认没有 查看日志命令 这个命令其实也可以查
  • 数学建模 优质的信息检索渠道和工具

    文章目录 一 前言 二 主要内容 三 总结 CSDN 叶庭云 https yetingyun blog csdn net 一 前言 优质的信息检索渠道和工具对数学建模比赛获奖有着重要的影响 以下是从理论上分析这一影响的几个主要方面 知识获取
  • vs 2019输出中文乱码解决

    参考 http t csdn cn YDG6B
  • 股市中的内盘、外盘、跌幅、震幅、现手、总手、换手是什么意思?

    外盘即买盘 内盘即卖盘 内盘即卖盘要卖掉 有人买就以这个成交价设为买入价 外盘即买盘要买进 有人卖就以这个成交价设为卖出价 总手就是成交量 1个交易日的买卖总量 即等于外盘 内盘 成交量 总手 量比 在查看分时走势图时候 可根据右键菜单选择
  • hadoop3.0.3搭建与入门(添加删除;调度-节点)

    hadoop版本 apache cloudera CDH版 Hortonworks HDP版 国内对CDH用的多 一般用3 0 单机版 scp hadoop 3 0 3 tar gz jdk 8u181 linux x64 tar gz s
  • 递归算法(二分查找)

    递归也算循环的一种 递归 你打开面前这扇门 看到屋里面还有一扇门 你走过去 发现手中的钥匙还可以打开它 你推开门 发现里面还有一扇门 你继续打开它 若干次之后 你打开面前的门后 发现只有一间屋子 没有门了 然后 你开始原路返回 每走回一间屋
  • RNN循环神经网络的Matlab模拟和训练

    RNN循环神经网络的Matlab模拟和训练 循环神经网络 RNN 是一种适用于序列数据的神经网络 RNN 在处理时间序列数据方面非常适用 如自然语言处理 股票价格预测等 本文将介绍如何使用 Matlab 来进行 RNN 的模拟和训练 在 M
  • 大O表示法及旅行者问题

    算法的运行时间 运行时间增速 不同算法随规模的增大而增大的速度不同 我们需要比较不同算法的运行时间的增速 大O表示法 类比数据结构中的时间复杂度 比较操作数 其体现了算法运行时间的增速 这种表示法体现了算法在最糟情况下的运行时间 这不就是时
  • 全新升级!讯飞星火认知大模型V2.0,你准备好了吗?

    前言 AI大模型正在全球掀起新一轮的技术革命与商业浪潮 从技术突破到应用落地 加速改变着我们的生活与产业 依托通用人工智能领域的持续深耕和系统性创新 科大讯飞于5月6日正式发布星火认知大模型 并于6月9日迅速完成迭代升级 受到用户持续好评
  • 软件测试环境的搭建

    前言 测试环境是QA开展测试工作的前置条件 稳定和可控的测试环境 可以使测试人员在执行测试用例时无需花费额外的时间去维护 有些公司运维或者研发部门会帮忙准备好测试环境 但是QA如果一味依赖其他部门 会局限测试工作的开展 一 什么是测试环境
  • 【PASS】析因设计样本量计算

    b站视频 working
  • 软件设计和硬件开发 部分学习网站

    1 单片机教程网 http www 51hei com 2 博客园 https www cnblogs com 3 各种程序语言基础知识 https www runoob com cprogramming c scope rules htm
  • Linux运维基础--常见命令

    Linux运维基础 常见命令 linux的发行版本介绍 Linux 内核 kernel 版本主要有 4 个系列 分别为 Linux kernel 2 2 Linux kernel 2 4 Linux kernel 2 6 Linux ker
  • 贪心——字典序最小问题

    https vjudge net problem POJ 3617 题目简单理解就是 给定长度为N的字符串为S 要构造一个长度为N的字符串T 起初 T 是一个空串 随后反复进行下列任意操作 从S的头部删除一个字符串 加到T的尾部 从S的尾部
  • 教与学(TlBO)算法路径规划应用

    是一种基于群体的启发式优化算法 不需要任何算法特定参数 这种方法模拟了传统的课堂教学过程 整个优化过程包括教师阶段和学习者阶段 在教师阶段 每个学生都向最优秀的个体进行学习 在学习阶段 每个学生都以随机的方式向其他学生学习
  • k8s--基础--23.3--认证-授权-准入控制--授权

    k8s 基础 23 3 认证 授权 准入控制 授权 1 介绍 Kubernetes的授权是基于插件形式的 其常用的授权插件有以下几种 1 Node 节点认证 2 ABAC 基于属性的访问控制 3 RBAC 基于角色的访问控制 4 Webho
  • 在IDEA中用jdbc技术通过配置文件连接mysql数据库连接池

    File gt project Structure gt Libraries gt 点 号 gt java gt 选择在电脑中下载druid 1 1 9 jar及以上版本的德鲁伊jar包和mysql connector java 8 0 0
  • MySQL-锁详解

    锁 锁是计算机协调多个进程或线程并发访问某一资源的机制 在数据库中 除传统的计算资源 如CPU RAM I O等 的争用以外 数据也是一种供许多用户共享的资源 如何保证数据并发访问的一致性 有效性是所有数据库必须解决的一个问题 锁冲突也是影
  • 算法刷题-双指针-反转链表

    反转链表的写法很简单 一些同学甚至可以背下来但过一阵就忘了该咋写 主要是因为没有理解真正的反转过程 206 反转链表 力扣题目链接 题意 反转一个单链表 示例 输入 1 gt 2 gt 3 gt 4 gt 5 gt NULL 输出 5 gt