【LeetCode】019. Remove Nth Node From End of List

描述:删除单链表的倒数第n个节点

分析:

  • 主要思路是用两个指针遍历单链表,先让右指针前进n个节点,然后再让两个指针同步前进,这样右指针到达表尾null的时候,左指针的下一个即是要删除的节点
    for (int i = 1; i <= n + 1; i++) {
        right = right.next;
    }

    for (; right != null; right = right.next) {
        left = left.next;
    }
  • 为了消除第一个节点的特殊性,用一个头节点指向它
    ListNode ahead = new ListNode(0);
    ahead.next = head;
  • 删除节点
    left.next = left.next.next;

完整实现:

public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode ahead = new ListNode(0);
    ahead.next = head;

    ListNode left = ahead;
    ListNode right = ahead;

    for (int i = 1; i <= n + 1; i++) {
        right = right.next;
    }

    for (; right != null; right = right.next) {
        left = left.next;
    }

    left.next = left.next.next;
    return ahead.next;
}
posted @ 2016-05-17 12:11  _lazyval  阅读(105)  评论(0编辑  收藏  举报