算法学习 二十四天 链表

 


目录

 一、题目

1、题目描述

2、基础框架

3、原题链接

二、解题报告

1、思路分析

2、代码详解

三、本题小知识


 一、题目


1、题目描述

给定单链表的头节点 head ,请反转链表,并返回反转后的链表的头节点。

示例 1:

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

示例 2:

输入:head = [1,2]
输出:[2,1]

示例 3:

输入:head = []
输出:[]

2、基础框架

   Java 版本给出的基础框架代码如下:   

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
}

3、原题链接

    LeetCode 剑指 Offer II 024. 反转链表

二、解题报告


1、思路分析

依次将链表元素取出

并用头插法将其插入新链表

头差法原理图:


2、代码详解

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null){
            return null;
        }
        ListNode node=new ListNode(0);
        //虚结点之向链表的头节点
        node.next=head;
        //定义结点pre代表head结点进行遍历
        ListNode pre=head;
        ListNode cur=head.next;
        while(cur!=null){
            //删除cur的结点
            head.next=cur.next;
            //头插法将cur插入 node
            cur.next=node.next;
            node.next=cur;
            //更新cur结点
            cur=head.next;
        }
        return node.next;
    }
}

三、本题小知识

    链表,反转,头插

猜你喜欢

转载自blog.csdn.net/qq_43846797/article/details/124735364