翻轉一個鏈表
- 樣例:
給出一個鏈表1->2->3->null,這個翻轉后的鏈表為3->2->1->null
思路:必須要有三個節點。cur,一個保存下一次要訪問的節點,before,一個是這一次斷開的哪個節點,last是斷開的這個點before要連接到的那個點。
public class Solution {
/**
* @param head: The head of linked list.
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode cur=head;
ListNode last=null;
ListNode before=null;
while(cur!=null){
last=before;
before=cur;
cur=cur.next;
before.next=last;
}
return before;
}
}