每天一道劍指offer-反轉鏈表

  • 2019 年 10 月 4 日
  • 筆記

今天的題目 每天的題目見github(看最新的日期): https://github.com/gzc426 具體的題目可以去牛客網對應專題去找。

昨天的題解

題目

每天一道劍指offer-反轉鏈表 來源:牛客網對應專題

題目詳述

輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。

題目詳解

思路

  • 先反轉第一個節點;
  • 然後後面的依次反轉;

程式碼

/*  /*  public class ListNode {      int val;      ListNode next = null;        ListNode(int val) {          this.val = val;      }  }*/  public class Solution {      public ListNode ReverseList(ListNode head) {          if(head == null || head.next == null)              return head;          ListNode p = head.next;//p指向頭結點的下一個節點          ListNode pre = head;//p節點的前一個節點pre.          pre.next = null;//先把第一個節點當做最後一個節點,置位null          ListNode next = p.next;//然後next記錄p的下一個節點          while(p != null)          {              p.next = pre;//p當前節點指向前一個pre,完成這兩個節點的反轉              pre = p;//然後pre往後移動              p = next;//然後p指向next 這樣都開始往後移動了。              if(p != null)//只要下一個節點不為空,next才可以賦值成下一個節點。                  next = p.next;          }          head = pre;          return head;      }  }

程式碼截圖(為了避免程式碼排版錯亂