leetcode系列-删除链表的倒数第N个节点(这题我会做系列)

分类:链表

难度:medium

方法:双指针

  1. 删除链表的倒数第N个节点

给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:

给定的 n 保证是有效的。

进阶:

你能尝试使用一趟扫描实现吗?

题解

终于有道完全没有看题解,自己做出来的medium了,哈哈哈
将两个指针a,b指向链表头部
维护一个整数idx,保存当前的节点是第几个节点;
首先使用指针a遍历链表,直到第n+1个节点(idx>n);
然后同时往后继续移动a和b,等到a到达链表尾部;a到达尾部时,b正好在倒数n+1节点,直接将b的next指向next.next即可
注意:需要注意的是,如果idx=n,a已经遍历完整个链表了,说明需要删掉的是头部节点,直接返回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
        """
        if not head or not head.next:
            return 
        pos = head
        pos1 = head
        idx = 0
        while pos:
            if idx>n:
                pos1 = pos1.next
            pos = pos.next
            idx += 1
        if idx<=n:
            head = head.next
        else:
            pos1.next = pos1.next.next
        return head
发布了41 篇原创文章 · 获赞 0 · 访问量 6154

猜你喜欢

转载自blog.csdn.net/Yolo_C/article/details/104838692