剑指Offer:反转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。

解题思路

递归

public class Solution {
    public ListNode ReverseList(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode next = head.next;
        head.next = null;
        ListNode newHead = ReverseList(next);
        next.next = head;
        return newHead;
    }

    public class ListNode {
        int val;
        ListNode next = null;
        ListNode(int val) {
            this.val = val;
        }
    }
}

迭代

public class Solution2 {
    public ListNode ReverseList(ListNode head) {
        ListNode newList = new ListNode(-1);
        while (head != null) {
            ListNode next = head.next;
            head.next = newList.next;
            newList.next = head;
            head = next;
        }
        return newList.next;
    }

    public class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }
}
本站所有文章均来自互联网,如有侵权,请联系站长删除。极客文库 » 剑指Offer:反转链表
分享到:
赞(0)

评论抢沙发

评论前必须登录!