其他分享
首页 > 其他分享> > leetcode 206.反转链表

leetcode 206.反转链表

作者:互联网

leetcode 206.反转链表

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

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

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

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

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

示例2:

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

解法&思想:

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;
    }
}

标签:head,cur,206,next,链表,节点,null,leetcode
来源: https://blog.csdn.net/qq_32756029/article/details/123608593