lc206.java 1.1 KB
Newer Older
L
liu13 已提交
1 2 3 4 5 6 7 8
package code;
/*
 * 206. Reverse Linked List
 * 题意:链表反转
 * 难度:Easy
 * 分类:Linked List
 * 思路:2中方法:设置一个快走一步的快指针,注意赋值操作顺序。还有一种递归的方法。
 * Tips:递归的方法有点绕,多看下
L
liu13 已提交
9
 *      lc25, lc206
L
liu13 已提交
10 11 12 13 14 15 16 17 18
 */
public class lc206 {
    public class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

    public ListNode reverseList(ListNode head) {
L
liu13 已提交
19 20
        ListNode pre = null;    //头结点变尾节点,指向null
        while(head!=null){
L
liu13 已提交
21
            ListNode next = head.next;
L
liu13 已提交
22 23
            head.next = pre;
            pre = head;
L
liu13 已提交
24 25
            head = next;
        }
L
liu13 已提交
26
        return pre;
L
liu13 已提交
27 28 29 30 31
    }

    public ListNode reverseList2(ListNode head) {   //递归
        return reverseListInt(head, null);
    }
L
liu13 已提交
32
    private ListNode reverseListInt(ListNode head, ListNode pre) {
L
liu13 已提交
33
        if (head == null)
L
liu13 已提交
34
            return pre;
L
liu13 已提交
35
        ListNode next = head.next;
L
liu13 已提交
36
        head.next = pre;
L
liu13 已提交
37 38 39
        return reverseListInt(next, head);  //尾递归,操作已经完成,最后返回最后结果罢了
    }
}