反转链表

  AcWing打卡活动

《剑指Offer》打卡活动 

周三第一题   反转链表

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 * 
 * 思路
 * 需要三个节点
 * 为了防止节点断开,我们需要知道当前遍历节点的上一个节点和下一个节点
 * 如下例子 三个节点不停移动
 * 
 * 例子
 * node1 node2 node3
 * 将node2的next指向node1,这时,node2和node3是断开的
 * 所以这时我们需要保存node3后面的节点node4
 * node2 node3 node4
 * 将node3指向node2,这样不断重复
 * 
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null) {
            return null;
        }
        
        // 使用此种方法至少要保证有两个节点
        if(head.next == null) {
            return head;
        }
        // 中心节点指向头结点的下一个
        ListNode hubNode = head.next;
        ListNode nextNode = null;
        // 左节点指向头结点
        ListNode preNode = head;
        preNode.next = null;
        while(hubNode != null) {
            // 右节点指向中心节点的下一个节点
            nextNode = hubNode.next;
            // 开始反转列表
            hubNode.next = preNode;
            if(nextNode == null) {
                break;
            }
            // 三个节点都向后移动一位
            preNode = hubNode;
            hubNode = nextNode;
            nextNode = nextNode.next;
        }


        return hubNode;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值