c# LeetCode 206. 反转链表(链表)

本文介绍了使用C#实现链表反转的两种方法:迭代和递归。通过具体代码示例,展示了如何将一个单向链表的节点顺序进行反转,提供了一种高效且易于理解的解决方案。

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

原题链接:https://leetcode-cn.com/problems/reverse-linked-list/

执行用时: 156 ms, 在Reverse Linked List的C#提交中击败了55.73% 的用户

c#解题:

public class Solution {
    public ListNode ReverseList(ListNode head) {
        ListNode header = new ListNode(-1);
			ListNode prev = null;
			ListNode cur = head;
			while (cur!=null)
			{
				ListNode next = cur.next;
				cur.next = prev;
				prev = cur;
				cur = next;
			}
			return prev;
    }
}

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */

c#递归:

执行用时: 156 ms, 在Reverse Linked List的C#提交中击败了55.73% 的用户

 public 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;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值