174. Remove Nth Node From End of List

题目

https://www.lintcode.com/problem/remove-nth-node-from-end-of-list/description?_from=ladder&&fromId=2

实现

  1. 设置两个指针,先让后一个指针走 n 步
  2. 因为要找到删除节点的前一个节点,所以第一个指针往前走一步(-1 步)
  3. 然后两个指针同时走,直到后一个指针走到头,删除节点即可

代码

class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next


class Solution:
    """
    @param head: The first node of linked list.
    @param n: An integer
    @return: The head of linked list.
    """

    def removeNthFromEnd(self, head, n):
        result = ListNode(0)
        result.next = head

        # 先走 n 步
        for i in range(n):
            head = head.next

        # 相当于先往后退了一步
        preDelete = result

        while head is not None:
            preDelete = preDelete.next
            head = head.next

        # 删掉对应的节点
        preDelete.next = preDelete.next.next

        # 返回最初节点
        return result.next

你可能感兴趣的:(174. Remove Nth Node From End of List)