一、题目描述
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表:1->2->3->4->5,和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5
方法一:两遍遍历,第一遍求出链表长度
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
first = head
length = 0
while first:#求长度
length += 1
first = first.next
if length == 1:#如果长度为1,则n等于1
head = None
return head
if length == n:#如果长度和n相等,则删除的是第一个节点
head = head.next
return head
flag = 1
pre = head
cur = head.next
while (flag < length - n):
flag += 1
pre = cur
cur = cur.next
pre.next = cur.next
return head
原文:https://www.cnblogs.com/always-fight/p/10302641.html