牛客NC78反转链表 (头插法插入)

题目链接
在这里插入图片描述
把头结点下一个指向null 头结点后面的所有结点依次插入到头结点前

    public ListNode ReverseList(ListNode head) {
    
    
        if(head == null || head.next == null) return head;
        ListNode dummyNode = new ListNode(0);
        ListNode second = head.next;
        head.next = null;
        dummyNode.next = head;
        while(second!=null){
    
    
            ListNode newHead = new ListNode(second.val);
            second = second.next;
            newHead.next = dummyNode.next;
            dummyNode.next = newHead;
        }
        return dummyNode.next;
    }

猜你喜欢

转载自blog.csdn.net/qq_43434328/article/details/114896770
今日推荐