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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011296723/article/details/81711719

《剑指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);
    

    }
    }

猜你喜欢

转载自blog.csdn.net/u011296723/article/details/81711719
今日推荐