LeetCode Logo

206. 反转链表

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

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

示例 1:

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

示例 2:

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

示例 3:

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

提示:

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

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

思路:迭代法或递归

C#实现迭代法:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution {
    public ListNode ReverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while(cur != null) {
            // 需要保存下个节点,因为下个节点的next指针会被改变指向pre节点,从而实现反转
            // 若不保存,后面就无法更新cur节点使其继续往后遍历
            ListNode tempNext = cur.next;
            cur.next = pre;
            // 更新pre和cur节点
            pre = cur;
            cur = tempNext;
        }
        return pre;
    }
}

C#实现递归法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
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;
        // 头的的下个节点是null
        head.next = null;

        return newHead;
    }
}

Subscribe for New Articles!

Leave a Comment

Your email address will not be published. Required fields are marked *