【LeetCode】手撕系列—206. 反转链表_三个指针



1- 思路

  • 定义三个指针
  • prev:记录 cur 的前一个结点
  • cur:记录当前需要翻转的结点
  • tmp:记录 cur 的 next 防止遍历过程中找不到链表的剩余部分

2- 题解

⭐反转链表 ——题解思路

在这里插入图片描述

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode cur = head;
        ListNode tmp = null;
        while(cur!=null){
            tmp = cur.next;

            cur.next = prev;
            prev = cur;
            cur = tmp;
        }
        return prev;
    }
}

3-ACM模式

public class reverseLink {

    static class ListNode{
        int val;
        ListNode next;
        ListNode(){}
        ListNode(int x){
            val = x;
        }
    }

    public static ListNode reverse(ListNode head){
        ListNode prev = null;
        ListNode cur = head;
        ListNode tmp = null;
        while(cur!=null){
            tmp = cur.next;

            cur.next = prev;
            prev = cur;
            cur = tmp;
        }
        return prev;
    }


    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入链表长度n");
        int n = sc.nextInt();
        ListNode head=null ,tail=null;
        for(int i=0; i < n;i++){
            ListNode newNode = new ListNode(sc.nextInt());
            if(head==null){
                head = newNode;
                tail = newNode;
            }else{
                tail.next = newNode;
                tail = newNode;
            }
        }
        ListNode forRes  = reverse(head);

        System.out.println("翻转后的链表为:");
        while(forRes!=null){
            System.out.print(forRes.val+" ");
            forRes = forRes.next;
        }
    }
}

相关推荐

  1. leetcode206.

    2024-04-06 13:58:03       65 阅读
  2. LeetCode206

    2024-04-06 13:58:03       48 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-06 13:58:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-06 13:58:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-06 13:58:03       82 阅读
  4. Python语言-面向对象

    2024-04-06 13:58:03       91 阅读

热门阅读

  1. LeetCode207、210 课程表(图 dfs 拓扑排序)

    2024-04-06 13:58:03       40 阅读
  2. git 如何删除本地和远程分支

    2024-04-06 13:58:03       36 阅读
  3. 【DevOps工具篇】Keycloak中设置LDAP认证

    2024-04-06 13:58:03       40 阅读
  4. 基于单片机的USB 通信电磁锁控制系统设计

    2024-04-06 13:58:03       40 阅读
  5. 如何面对微服务在部署和管理上的挑战

    2024-04-06 13:58:03       37 阅读
  6. 4层板学习笔记

    2024-04-06 13:58:03       38 阅读
  7. 408经验贴

    2024-04-06 13:58:03       30 阅读
  8. Ubuntu安装 SNAP及SNAP常用命令

    2024-04-06 13:58:03       40 阅读
  9. Matlab安装完成后打开后闪退

    2024-04-06 13:58:03       32 阅读
  10. 计算机视觉基础入门指南

    2024-04-06 13:58:03       40 阅读
  11. ts之接口和泛型概念

    2024-04-06 13:58:03       37 阅读