LeetCode 206. 反转链表(C#实现)——链表,递归,迭代

一、问题

https://leetcode-cn.com/problems/reverse-linked-list/

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

二、GitHub实现:https://github.com/JonathanZxxxx/LeetCode/blob/master/ReverseListClass.cs

  Blog:https://www.cnblogs.com/zxxxx/

三、思路

  1、迭代:每次循环,都将当前节点指向它前面的节点,然后当前节点和前节点后移

  2、递归:假设链表的其余部分已经被反转,需要考虑的就是如何反转前面的部分

四、代码实现

 1     public class ReverseListClass
 2     {
 3         public class ListNode
 4         {
 5             public int val;
 6             public ListNode next;
 7             public ListNode(int x) { val = x; }
 8         }
 9 
10         /// <summary>
11         /// 迭代
12         /// </summary>
13         /// <param name="head"></param>
14         /// <returns></returns>
15         public ListNode ReverseList(ListNode head)
16         {
17             ListNode prev = null;//前指针节点
18             var current = head;//当前指针节点
19             //每次循环,都将当前节点指向它前面的节点,然后当前节点和前节点后移
20             while (current != null)
21             {
22                 var temp = current.next;//临时节点,暂存当前节点的下一节点,用于后移
23                 current.next = prev;//将当前节点指向它前面的节点
24                 prev = current;//前指针后移
25                 current = temp;//当前指针后移
26             }
27             return prev;
28         }
29 
30         /// <summary>
31         /// 递归
32         /// </summary>
33         /// <param name="head"></param>
34         /// <returns></returns>
35         public ListNode ReverseList2(ListNode head)
36         {
37             //递归终止条件是当前为空,或者下一个节点为空
38             if (head == null || head.next == null) return head;
39             var node = ReverseList2(head.next);
40             //head为4,head.next.next=head,node为4->5->4
41             head.next.next = head;
42             //head.next为空,防止链表循环,node为5->4
43             head.next = null;
44             //返回5->4,此时链表为1->2->3->4<-5
45             //下次循环,head为3,head.next.next=head,node为3->4->3
46             //head.next为空,node为4->3
47             //返回4->3,此时链表为1->2<-3<-4<-5
48             return node;
49         }
50     }
原文地址:https://www.cnblogs.com/zxxxx/p/12162363.html