#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time: 2019/3/13
# @Author: xfLi
# The file...
"""
问题分析:
(1)设置两个指针,一个在前,先走n步,然后两个指针同时向前走,直到第一个指针走到头。
(2)那么现在,第二个指针,就是前面要删除的结点。
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def removeNthFromEnd(head, n):
if not head: return None
second = first = head
for i in range(n): # 第一个指针先走 n 步
first = first.next
if first is None:
return second.next
while first.next: # 然后同时走,直到第一个指针走到头
first = first.next
second = second.next
second.next = second.next.next # 删除相应的结点
return head
【LeetCode】19.删除链表的倒数第N个节点
猜你喜欢
转载自blog.csdn.net/qq_30159015/article/details/88537283
今日推荐
周排行