1. 程式人生 > >[leetcode]206.Reverse Linked List

[leetcode]206.Reverse Linked List

class init linked example turn you ext ati implement

題目

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