LeetCode-206.ReverseLinked List

本文详细讲解了链表逆序的两种实现方法:迭代与递归,并提供了完整的代码示例。此外,还介绍了两两交换链表结点及每k个节点翻转的进阶题目,附带LeetCode相关题目链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:A linked list can be reversed either iteratively or recursively. Could you implement both?

public ListNode reverseList(ListNode head) {//链表 迭代 my
        ListNode nhead = null;
        ListNode curr = head;
        while(null!=curr){
            head=head.next;
            curr.next=nhead;
            nhead=curr;
            curr=head;
        }
        return nhead;
    }  

  

递归

public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode p = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return p;
}

 

进阶题

两两交换链表中的结点 LeetCode24 https://www.cnblogs.com/zhacai/p/10559271.html 

每 k 个节点一组翻转链表 LeetCode25  https://www.cnblogs.com/zhacai/p/10563446.html

转载于:https://www.cnblogs.com/zhacai/p/10429295.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值