首页 > 代码库 > 翻转链表

翻转链表

/**
     * 翻转双向链表
     * 需要记录翻转后的下一个节点
     * @param head
     * @return
     */
    public DoubleNode reverserList(DoubleNode head){
        DoubleNode pre = null;
        DoubleNode next = null;
        while(head != null){
            next = head.next;
            head.next = pre;
            head.last = next;
            pre = head;
            head = next;
        }
        return pre;
    }
/**
     * 翻转单链表
     * 需要记录翻转后的下一个节点
     * @param head
     * @return
     */
    public static ListNode reverse2(ListNode head){
        ListNode pre = null;
        ListNode next = null;
        while(head != null){
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

 

翻转链表