Remove Nth Node From End of List

题目链接

Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?

python代码实现:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def removeNthFromEnd(self, head, n):
        cur = pre = head
        for _ in range(n):
            cur = cur.next
        if not cur:
            return head.next
        while cur.next:
            cur = cur.next
            pre = pre.next
        pre.next = pre.next.next
        return head
实现思路:

这道题让我们移除链表倒数第N个节点,限定n一定是有效的,即n不会大于链表中的元素总数。还有题目要求我们一次遍历解决问题,那么就得想些比较巧妙的方法了。比如我们首先要考虑的时,如何找到倒数第N个节点,由于只允许一次遍历,所以我们不能用一次完整的遍历来统计链表中元素的个数,而是遍历到对应位置就应该移除了。那么我们需要用两个指针来帮助我们解题,pre和cur指针。首先cur指针先向前走N步,如果此时cur指向空,说明N为链表的长度,则需要移除的为首元素,那么此时我们返回head->next即可,如果cur存在,我们再继续往下走,此时pre指针也跟着走,直到cur为最后一个元素时停止,此时pre指向要移除元素的前一个元素,我们再修改指针跳过需要移除的元素即可。


本地调试时代码,但是和letcode线上实现的有出处,仅供参考

# 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
        """
        count = 0
        p = head
        while p.next:
            count += 1
            p = p.next
        if count == 1 and n >= 1:
            return None
        # 把第count-n+1个删除
        p = head
        for i in range(count - n - 1):
            p = p.next
        if n != 0:
            p.next = p.next.next
        return head
	h = ListNode(1)
	point = h
	n = 5
	for i in range(n):
	    curr = ListNode(i + 2)
	    point.next = curr
	    point = curr
	point = h
	while point.next:
	    # print(point.val)
	    point = point.next
	s = Solution()
	res = s.removeNthFromEnd(h, 2)
	point = res
	if point == None:
	    print(None)
	else:
	    while point.next:
	        print(point.val)
	        point = point.next
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

. . . . .

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值