LeetCode第19題,刪除鏈表倒數的第n個結點.java
兩趟掃描的思想很簡單,第一趟掃描肯定長度,第二趟掃描定位到目標結點並進行刪除操做.node
public ListNode removeNthFromEnd(ListNode head, int n) { if(head == null || head.next == null) return null; ListNode head_copy = head; int length = 0; while(head != null) { head = head.next; ++length; } head = head_copy; ListNode before = head; int i = 0; for(;i<length-n;++i) { before = head; head = head.next; } if(i == 0) return head.next; else before.next = before.next.next; return head_copy; }
固然,來刷題的話不能就這樣就算了,確定得把它弄成一趟掃描,對吧?
兩趟掃描的目的是獲取長度再進行定位,所以,爲了能一次定位,能夠使用兩個頭指針,對於給定的n,先讓第一個頭指針訪問n次,第二個頭指針不動,當第一個頭指針訪問n次後,第一個頭指針繼續訪問直到最後一個,第二個頭指針與第一個頭指針並行訪問,這樣,當第一個頭指針訪問到最後一個時,第二個頭指針就指向倒數第N個節點.git
public ListNode removeNthFromEnd(ListNode head, int n) { ListNode a = head; ListNode b = head; ListNode t = head; for(int i=0;i<n;++i) a = a.next; if(a == null) return head.next; while(a != null) { t = b; a = a.next; b = b.next; } t.next = t.next.next; return head; }
總的來講這個只須要一趟掃描便可,針對只有兩個結點或者一個結點的要判斷一下.github
githubide
碼雲指針