leetcode 206. 反转链表

2019-06-02  本文已影响0人  topshi

题目描述

反转一个单链表。
相关话题: 链表   难度: 简单

示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

思路 1:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode newHead = null;
        for(ListNode p = head;p != null;){
            ListNode x = p;
            p = x.next;
            x.next = newHead;
            newHead = x;
        }
        return newHead;
    }
}

思路 2:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        for(ListNode p = head;p.next != null;){
            ListNode x = p.next;
            p.next = x.next;
            x.next = head;
            head =x;
        }
        return head;
    }
}

思路 3: 递归

 ListNode newHead = reverseList(head.next);

此时,newHead是指向节点5
然后递归栈中继续执行栈顶的栈帧

要反转它,很简单,

       head.next.next = head;
       head.next = null;

然后变成,


直接返回newHead
继续执行栈顶栈帧,head->3->4->5->NULL,此时链表信息为

执行完
       head.next.next = head;
       head.next = null;

变成



依次执行直至递归栈为空。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}
上一篇下一篇

猜你喜欢

热点阅读