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

//方案一:測試

public class Solution {code

public ListNode ReverseList(ListNode head) {

       ListNode cur=head;
       ListNode temp=null;
       ListNode pre=null;
       
       while(cur!=null){
           temp=cur.next;
           cur.next=pre;
           pre=cur;
           cur=temp;
       }
    
    return pre;
}

}開發

//方案二:io

public class Solution {class

public ListNode ReverseList(ListNode head) {

      
       ListNode temp=null;
       ListNode pre=null;
       
       while(head!=null){
           temp=head.next;
            head.next=pre;
           pre=head;
           head=temp;
       }
    
    return pre;
}

}變量

推薦用方案一:方案二是我爲了測試實現逆序須要最少的臨時變量爲2個,而方案二改變別人給入的值,通常開發不推薦這麼作List

相關文章
相關標籤/搜索