反轉鏈表

題目描述
輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。

思路:

假設一個鏈表 A -> B ->C,則反轉後爲 C -> B -> A

new兩個新節點,一個pre爲反轉鏈表的表頭,另一個tmp遍歷當前鏈表用

每當tmp指向新的節點時,執行以下操作:

  1. 將tmp指向的下一節點備份
  2. 改tmp指向pre
  3. pre = tmp
  4. tmp = 備份的下一節點
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        
        ListNode pre = null;
        
        ListNode tmp = head;
        
        if(head == null || head.next == null){
            
            return head;
            
        }else{
            
            while(tmp != null){
                
                ListNode next = tmp.next;
                tmp.next = pre;
                pre = tmp;
                tmp = next;
            }
            return pre;
        }
        
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章