【算法】链表反转 -- 迭代解法

25 篇文章 1 订阅
14 篇文章 0 订阅
  • 前言在这里插入图片描述
 public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) { val = x; }
    }
  1. 存在一个新的链表的头结点
  2. 所有节点必须遍历一遍,但是每次遍历跟操作指针要分开,不然链表断裂后无法继续遍历,则存在游标cur
  • 整体实现

根据1和2可以写出以下代码,分析后错误明显 : 转链表后,current无法继续遍历

class Solution {
    /**
     * 将NULL也视作一个节点
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        // 新链表的头节点
        ListNode newPrev;
        // 创建游标遍历整个链表
        ListNode cur = head;
	
        while (cur.next != null) {
        	// 移动游标
           cur = cur.next
           // ......更多有关newPrev的逻辑
        }
        // cur遍历至旧的链表尾,即是新的链表头
        return cur;
    }
}
  • 细节分析在这里插入图片描述
    以上是第一个想到的办法,很显然,不可能实现。则有一下思考

1.按照整理实现的思路,current实现翻转,要将next指向新链表的头节点。
2.current指向上个节点后,新增的节点就为新链表的头节点。
3.新链表的第一个节点为null;

根据1、2、3有以下思路
在这里插入图片描述
显然在操作current指针时,需要新建个指针保留断开连接后的子链表
在这里插入图片描述

完成以上步骤后
在这里插入图片描述
1.不论current还是childList都是为了遍历子链表,而之前的节点已断开,函数返回newPre才是翻转后的链表头节点
2.当current == null 的时候,newPre刚好指向完整的新链表,所以修改迭代条件为while(cur != null)

  • 最终代码
class Solution {

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) { val = x; }
    }

    /**
     * 将NULL也视作一个节点
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        // 若把NULL也作为一个节点的话,NULL是新的链表的第一个头节点
        ListNode newPrev = null;
        // 创建游标遍历整个链表
        ListNode cur = head;

        while (cur != null) {
            ListNode childList = cur.next;
            cur.next = newPrev;
            newPrev = cur;
            cur = childList;
        }
        return newPrev;
    }
}

时间复杂度:O(n) 空间复杂度:O(1)

  • 拓展

链表反转递归解法见:

https://blog.csdn.net/chenghan_yang/article/details/94908013

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值