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

猜你喜欢

转载自www.cnblogs.com/shinjia/p/9785131.html