0
点赞
收藏
分享

微信扫一扫

leetcode 206.反转链表

草原小黄河 2022-03-20 阅读 49

leetcode 206.反转链表

示例1:
在这里插入图片描述

示例2:
在这里插入图片描述

示例2:

解法&思想:

1.迭代。
每次将当前指针cur指向pre,如果直接将cur.next 变成了cur-pre,这样会造成cur.next节点丢失需要先将cur.next保存下来。,

class Solution {
    public ListNode reverseList(ListNode head) {
        // 为空
        if(head == null){
            return head;
        }
        ListNode newhead = null;
        while(head != null) {
             // 保存当前节点的下一个节点
            ListNode next = head.next;
            // 将当前节点的next指向pre节点,第一个指向null
            head.next = newhead;
            // 移动新的头结点至cur节点的位置
            newhead = head;
            // cur节点移动
            head = next;   
        }
        return newhead;
    }
}
举报

相关推荐

0 条评论