剑指Offer编程题(Java实现)——反转链表

题目描述

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

思路一

使用头插法迭代进行反转

实现

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

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        ListNode newHead = new ListNode(-1);
        while(head != null){
            ListNode tmp = head.next;
            head.next = newHead.next;
            newHead.next = head;
            head = tmp;
        }
        return newHead.next;
    }
}

思路二

递归

实现

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

思路参考:https://www.nowcoder.com/discuss/198840

posted @ 2019-08-08 18:36  猫不夜行  阅读(279)  评论(0编辑  收藏  举报