1. 程式人生 > >劍指Offer:反轉鏈表

劍指Offer:反轉鏈表

turn inf 代碼 pub 需要 https sel .cn htm

劍指Offer:反轉鏈表

技術分享圖片

由於鏈表具有天然的遞歸結構,反轉鏈表其實很容易想到遞歸的方式。這裏暫不說了。說一下非遞歸的方式

非遞歸的方式

由於鏈表的next維持關系鏈的關鍵。反轉的過程就需要用額外的指針指向當前節點的前一節點和後一節點,不然的話就會發生斷鏈了。

圖示:

技術分享圖片

具體步驟偽代碼可為:

1. pNext指向當前節點的next以保持鏈 pNext = current.next;

2.當前節點的nextf指向前一節點(開始反轉)current.next = prev

3. prev 指針指向當前指針(即往後)prev = current

4. 當前的指針也往後 current = pNext;

步驟繁瑣點幫助理解,其實當前節點的指針其實就是head節點了。

代碼:

public class Solution {
    public ListNode reverseList(ListNode head) {
        //空判斷
        if(head == null)
            return head;
        //3個節點分別指向前一節點,當前節點,下一節點。
        ListNode prev = null;
        ListNode current = head;
        ListNode pNext;
        
//結束條件就是current節點成為了null時,那麽prev節點就成為反轉後的頭節點了。 while(current!=null){ pNext = current.next; current.next = prev; prev = current; current = pNext; } return prev; } }

遞歸的方式

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

gitHub源碼:反轉鏈表

圖片來源:https://www.cnblogs.com/csbdong/p/5674990.html

劍指Offer:反轉鏈表