首页 > 其他 > 详细

剑指 Offer 24. 反转链表

时间:2020-12-14 18:43:21      阅读:29      评论:0      收藏:0      [点我收藏+]
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        //判空
        if(head == null || head.next == null){
            return head;
        }
        //定义三个节点,他们的关系是  pre <--  now <-- next
        ListNode pre = null;
        ListNode now =head;
        ListNode next = null;

        while(now !=null){
            //保存当前节点的下一个节点信息
            next = now.next;
            //翻转链表的指向
            now.next = pre;
            //整体前移,进行下一次翻转
            pre = now;
            now = next;
        }
        return pre;
    }
}

 

剑指 Offer 24. 反转链表

原文:https://www.cnblogs.com/peanut-zh/p/14133988.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!