【leetcode】【206】Reverse Linked List

一、問題描述

Reverse a singly linked list.

click to show more hints.

Hint:

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

二、問題分析

這道題,最先想到的是迭代的方式。而迭代又有兩種方式:①保持從頭訪問過的元素先對位置不變,只改變指針的方向,頭結點需要單獨處理;②指針方向不變,改變元素的位置,即每訪問一個新的元素,就把新元素插到頭上;

遞歸的方法其實是從鏈表的最後邊依次改變指針的方向。

三、Java AC代碼

迭代①

public ListNode reverseList(ListNode head) {
        if (head==null || head.next == null) {
			return head;
		}
        ListNode pre = head;
        ListNode cur = head.next;
        pre.next = null;
        ListNode nxt = null;
        while(cur!=null){
        	nxt = cur.next;
        	cur.next = pre;
        	pre = cur;
        	cur = nxt;
        }
        return pre;
    }


迭代②

public ListNode reverseList(ListNode head) {
        if (head==null || head.next == null) {
			return head;
		}
        ListNode pivot = head;
        ListNode frontier = null;
        while(pivot.next!=null){
            frontier = pivot.next;
            pivot.next = frontier.next;
            frontier.next = head;
            head = frontier;
        }
        return head;
    }


遞歸

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章