leetCode206 反轉鏈表

反轉鏈表
在這裏插入圖片描述

  • 迭代法:雙指針;一個指針指向已經反轉鏈表的尾部一個指針指向待反轉鏈表的首部,不斷遍歷即可
 public ListNode reverseList(ListNode head) {

         if(head==null||head.next==null) return head;

        //已經反轉鏈表的尾部
        ListNode pre = null;
        //當前要反轉鏈表的頭部
        ListNode cur = head;
        //待反轉鏈表的下一節點
        ListNode next = cur.next;
        while(cur!=null){
            next=cur.next;
            cur.next=pre;
            pre= cur;
            cur = next;
        }

        return pre;

    }

  • 迭代
  public ListNode reverseList(ListNode head) {
 if(head==null||head.next==null) return head;

        ListNode cur = reverseList(head.next);

        head.next.next=head;
        head.next=null;
        return cur;

    }

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