Andy Back-end Dev Engineer

剑指offer-反转链表

2018-07-02

题目描述 输入一个链表,反转链表后,输出新链表的表头。

解题思路1

迭代

代码实现:

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

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    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;
    }
}

解题思路2

递归

代码实现:

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;
    }
}

Comments

Content