刪除連結串列指定位置節點
阿新 • • 發佈:2019-01-25
給定一個連結串列,刪除連結串列的倒數第 n 個節點,並且返回連結串列的頭結點。
示例:
給定一個連結串列: 1->2->3->4->5, 和 n = 2. 當刪除了倒數第二個節點後,連結串列變為 1->2->3->5.
進階:
你能嘗試使用一趟掃描實現嗎?
思路一:先得到一連結串列大小
public ListNode removeNthFromEnd_2(ListNode head, int n) { ListNode flagnode1 = head; ListNode flagnode2 = head; int m = 0; int i = 0; int leftflag = 0; while(flagnode1 != null){ m++; flagnode1 = flagnode1.next; } if(n == m){ return head.next; } else{ leftflag = m-n-1; } while(i != leftflag){ flagnode2 = flagnode2.next; i++; } flagnode2.next = flagnode2.next.next; return head; }
思路二:進階,雙指標,一個先走n步,另一個再走,直到另一個走到最後
public ListNode removeNthFromEnd_3(ListNode head, int n) { ListNode first = head; ListNode second = head; for(int i = 0; i<n+1;i++){ if(first != null) first = first.next; else return head.next; } while(first != null){ first = first.next; second = second.next; } second.next = second.next.next; return head; }