題目描述
輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。
解題思路
設置結點p與res,p結點用於指向下一節點,head是移動結點,將head.next不斷指向前一個結點。並且p不斷向後移動,res爲記錄當前所在結點,最後得到res,即爲反轉後的鏈表頭節點
源碼
/*
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)
return null;
ListNode p =head.next;
ListNode res = null;
while(head!=null){
head.next = res;
res = head;
head = p;
if(head != null)
p = head.next;
}
return res;
}
}