这篇文章为大家分享有关怎么删除链表倒数的第n个结点的一道题目。文章介绍了删除链表结点的解题思路和解题方法,希望大家通过这篇文章能有所收获。

两趟扫描

两趟扫描的思想很简单,第一趟扫描确定长度,第二趟扫描定位到目标结点并进行删除操作.

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个节点.

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;}

总的来说这个只需要一趟扫描即可,针对只有两个结点或者一个结点的要判断一下.