206. 反转链表

xkrivzooh2022年10月17日
小于 1 分钟

206. 反转链表

题目:

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

提示:

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

leetcode地址:https://leetcode.cn/problems/reverse-linked-list/open in new window

solution

/**
 * 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) {
            return head;
        }
        ListNode prev = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode temp = cur.next;
            cur.next = prev;
            prev = cur;
            cur = temp;
        }
        return prev;
    }
}
上次编辑于: 2022/10/18 16:24:09
Loading...