你今天学算法了吗?打卡第十八天

 


目录

 一、题目

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) {
}

提示:

  • 链表中节点的数目范围是 [0, 5000]
  • -5000 <= Node.val <= 5000

3、原题链接

    LeetCode 206. 反转链表

二、解题报告


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) {
        //前指针结点
        ListNode front=null;
        //当前结点
        ListNode cur = head;
        //遍历迭代,每次都将当前结点指向它前面的结点,然后把当前结点和前结点都后移
        while(cur!=null){
            //存储当前结点的下一个结点
            ListNode next=cur.next;
            //把当前结点指向前结点
            cur.next=front;
            //前结点后移
            front=cur;
            //当前结点后移
            cur=next;
        }
        return front;
    }
}

三、本题小知识

   链表

猜你喜欢

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