《剑指offer—面试题24:反转链表》

《剑指offer—面试题24:反转链表》
注明:仅个人学习笔记

/**
* 反转链表

  • SingleLinkedList:单链表操作
  • *
    */
    public class ReverseList24
    {
    public static Node reversrList(Node head)
    {

    // 头节点为空链表无法完成反转
    if (head == null)
    {
        return null;
    }
    
    // 链表节点唯一时,返回头节点
    if (head.next == null)
    {
        return head;
    }
    
    Node pReverseHead = null;
    Node pNode = head;
    Node preNode = null;
    
    while (pNode != null)
    {
        Node pNext = pNode.next;// 记录当前节点的下一节点
    
        if (pNext == null)// 如果当前节点的下一节点为空,说明当前节点为尾节点,也就是反链表翻转后的头节点
        {
            pReverseHead = pNode;
        }
    
        pNode.next = preNode;// 将当前节点指向其前一个节点
    
        preNode = pNode;// 现在的前一个节点就是当前节点
        pNode = pNext;// 当前节点为下一节点
    
    }
    
    return pReverseHead;
    

    }

    public static void main(String[] args)
    {
    SingleLinkedList list = new SingleLinkedList();

    list.addNode(1);
    list.addNode(2);
    list.addNode(3);
    list.addNode(4);
    list.addNode(5);
    list.addNode(6);
    
    Node n = reversrList(list.head);
    
    list.printList2(n);
    

    }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值