题解 | #反转链表#

反转链表

http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null || head.next == null){//特殊值处理,空链表,或者链表的长度为1
            return head; 
        }
        ListNode prep = null;  //保存当前节点的前驱节点
        ListNode next = head.next;  //保存当前节点的后继节点
        while (head != null){//遍历链表,head指向当前遍历的链表节点
            next = head.next;  //保存当前节点的后继节点
            head.next = prep;  //实现链表方向反转
            prep = head;  //前驱节点后移
            head = next;  //当前节点后移
        }
        return prep;//返回链表反转后的头指针
    }
}
全部评论

相关推荐

给🐭🐭个面试机会...:这b打广告打半年了,我真服了,装都不装了现在
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务