删除链表的倒数第N个节点
题目描述
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
解题方法
方法一:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
len_n=0
cur=head
while(cur):
cur = cur.next
len_n+=1
if len_n<2:
return None
if len_n-n==0:
nodes_next = head.next
else:
nodes_next = ListNode(head.val)
i=0
nodes_head = nodes_next
head_next = head
while(i<=len_n-n-1):
if i==len_n-n-1:
head_next = head_next.next
nodes_next.next = head_next.next
else:
head_next = head_next.next
#print(head_next.val)
nodes_next.next = ListNode(head_next.val)
nodes_next = nodes_next.next
i+=1
return nodes_head
方法二:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
len_n=0
cur=head
while(cur):
cur = cur.next
len_n+=1
if len_n<2:
return None
if len_n-n==0:
return head.next
else:
cur = head
i=0
while(i<=len_n-n-1):
if i==len_n-n-1:
cur.next = cur.next.next
break
else:
cur = cur.next
i+=1
return head
方法三:
快慢指针:
快指针比满指针早走n步
然后快慢指针同时起步,当快指针走到最末(n1==none and n1.next=none)的时候,慢指针走到倒数n的位置
快指针跳过n位置
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummyHead = ListNode(0)
dummyHead.next=head
n1 = dummyHead
n2 = dummyHead
while (n != 0) :
n2 = n2.next
n-=1
while (n2!=None and n2.next!= None):
n1 = n1.next
n2 = n2.next
n1.next = n1.next.next
return dummyHead.next