反转链表-leetcode

题目描述

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

示例 1:

img

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

示例 2:

img

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

示例 3:

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

提示:

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

解法一

思路:

迭代置换,p,q,r三个指针,转换q.next=p,之后p=q,q=r,r=r.next。

/**
 * 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 || head.next == null) return head;
        ListNode p,q,r;
        p = head;q=head.next;r=head.next.next;
        while(true){
            if(p==head)p.next=null;
            q.next=p;
            p=q;
            q=r;
            if(q==null) break;
            r=r.next;
        }
        return p;
    }
}

解法二

思路:

来自官方解答。

递归版本稍微复杂一些,其关键在于反向工作。假设链表的其余部分已经被反转,现在应该反转它前面的部分。设链表为:

image-20250928191656820

若从节点 image-20250928191725095image-20250928191741891 已经被反转,而我们正处于 image-20250928191754300

image-20250928191804311

我们希望 image-20250928191823248 的下一个节点指向 image-20250928191856362

所以,image-20250928191927213

需要注意的是 image-20250928191948351 的下一个节点必须指向 ∅。如果忽略了这一点,链表中可能会产生环

代码:

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}
posted @ 2025-09-28 19:21  狐狸胡兔  阅读(6)  评论(0)    收藏  举报