0
点赞
收藏
分享

微信扫一扫

链表 | LeetCode 206. 反转链表

四月Ren间 2022-03-30 阅读 88
java算法

206. 反转链表 - 力扣(LeetCode) (leetcode-cn.com)icon-default.png?t=M276https://leetcode-cn.com/problems/reverse-linked-list/

/**
 * 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 null;
        }
        ListNode cur = null, pre = head;
        while (pre != null) {
            ListNode swap = pre.next;
            pre.next = cur;
            cur = pre;
            pre = swap;
        }
        return cur;
    }
}

思路还是比较简单的,三个节点,一个在前,一个在后,一个用来交换,while循环过一遍。

举报

相关推荐

0 条评论