1. 程式人生 > >LeetCode刷題Easy篇反轉單鏈表

LeetCode刷題Easy篇反轉單鏈表

題目

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?

 

我的嘗試

迭代方式

主要是記得三個指標,下一個節點,前一個節點,當前節點

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    ListNode pre=null;
    ListNode nextTmp=null;
   
    public ListNode reverseList(ListNode head) {
         ListNode curr=head;
        while(curr!=null){
            nextTmp=curr.next;
            curr.next=pre;//剛開始pre為null,也對
            pre=curr;
            curr=nextTmp;
        }
        return pre;
        
        
    }
}

遞迴方式

遞迴方式比較詭異,舉例,比如

n1->n2->n3->n4->n5->n6

如果後半部分已經反轉了,設想遞迴如何進行:

n1->n2->n3->n4<-n5<-n6

逆轉的公式為: n3.next.next=n3;  n3.next=null

遞迴的出口條件為: head==null||head.next==null

所以遞迴寫法:

public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode p = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return p;
}