题目链接
https://leetcode.com/problems/remove-nth-node-from-end-of-list/
题目原文
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.Note:
Given n will always be valid.
Try to do this in one pass.
题目翻译
给定一个链表,删除从尾部开始数的第n个节点,并返回链表头部。
比如:给定链表1->2->3->4->5,以及 n = 2 , 删除节点后,链表变成 1->2->3->5。
注意:给定的n总是有效的;尽量在一遍遍历的情况下完成这道题。
思路方法
思路一
用两个指针,一个指针p从前到后扫描整个链表,一个指针q慢指针p的步数为n+1,那么当p指向尾部的Null时,指针q恰好指向要删除节点的前一个节点。由于可能删除头部节点,伪装一个新的头部方便操作。
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
new_head = ListNode(0)
new_head.next = head
fast = slow = new_head
for i in range(n+1):
fast = fast.next
while fast:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return new_head.next
思路二
题目并没有说不能修改节点的值,一个比较tricky的做法是:将倒数第n个节点前的节点的值依次后移,最后返回head.next即为所求。用递归实现了“倒着数”的操作。
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
def getIndex(node):
if not node:
return 0
index = getIndex(node.next) + 1
if index > n:
node.next.val = node.val
return index
getIndex(head)
return head.next
思路三
类似思路二,不过这次不再修改节点值,而是真正的删除倒数第n个节点。
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
def remove(node):
if not node:
return 0, node
index, node.next = remove(node.next)
next_node = node if n != index+1 else node.next
return index+1, next_node
ind, new_head = remove(head)
return new_head
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.youkuaiyun.com/coder_orz/article/details/51691267