🌗 206. 反转链表

吞佛童子2022年6月9日
  • algorithm
  • list
小于 1 分钟

🌗 206. 反转链表

难度: 🌗

问题描述

img_4.png


解法

/**
 * 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) {
        // 思路:
        // 虚拟节点辅助
        ListNode pre = null;
        ListNode cur = head;
        while(cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

输出

img_9.png

上次编辑于: 2022/6/20 下午8:24:47
贡献者: liuxianzhishou