題目描述
輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。
思路:
假設一個鏈表 A -> B ->C,則反轉後爲 C -> B -> A
new兩個新節點,一個pre爲反轉鏈表的表頭,另一個tmp遍歷當前鏈表用
每當tmp指向新的節點時,執行以下操作:
- 將tmp指向的下一節點備份
- 改tmp指向pre
- pre = tmp
- 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;
}
}
}