[leetcode]206.Reverse Linked List

Posted shinjia

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]206.Reverse Linked List相关的知识,希望对你有一定的参考价值。

题目

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

解法一

思路

链表逆转题,链表题在表头加一个头结点会比较好。第一种方法用非递归的方法,每次用tmp来保存要移动前面的结点,然后先删除tmp结点,然后把tmp结点插入到头结点后面即可。

代码

/**
 * 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) return head;
        ListNode fakehead = new ListNode(0);
        fakehead.next = head;
        while(head.next != null) {
            ListNode tmp = head.next;
            head.next = tmp.next;
            tmp.next = fakehead.next;
            fakehead.next = tmp;
        }
        return fakehead.next;
    }
}

解法二

思路

用递归的方法写.

代码

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


以上是关于[leetcode]206.Reverse Linked List的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 206 Reverse Linked List

Leetcode 206: Reverse Linked List

[LeetCode]206. Reverse Linked List

206. Reverse Linked List(LeetCode)

Leetcode92. Reverse Linked List II && 206. Reverse Linked List

Leetcode 206. Reverse Linked List