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

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

/**
* 反转链表

  • SingleLinkedList:单链表操作
    • Node:链表节点
    • 这两个实现类详见《剑指offer—面试题18:删除链表的节点》
      • https://blog.csdn.net/u011296723/article/details/81670532
  • *
    */
    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);
    

    }
    }

你可能感兴趣的:(剑指offer)