链表的反转

2019-08-26  本文已影响0人  Peter杰
//递归
        public ListNode reverseList(ListNode head) {
            if (head == null) {
                return null;
            }
            if (head.next==null) {
                return head;
            }
            ListNode newHead = reverseList(head.next);
            head.next.next = head;
            head.next = null;
            return newHead;
        }
        //非递归
        public ListNode reverseList2(ListNode head) {
            if (head == null) {
                return null;
            }
            if (head.next==null) {
                return head;
            }
            ListNode newHead = null;
            while (head != null) {
                ListNode tmp = head.next;
                head.next = newHead;
                newHead = head;
                head = tmp;
            }
            return newHead;
        }
上一篇 下一篇

猜你喜欢

热点阅读