LeetCode刷题-19——Remove Nth Node From End of List( 删除链表的倒数第N个节点 )

链接:

https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

题目:

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

Example:

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

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

Notes:

给定的 n 保证是有效的。
你能尝试使用一趟遍历实现吗?

解析:

典型的利用双指针法解题。首先让指针first指向头节点,然后让其向后移动n步,接着让指针sec指向头结点,并和first一起向后移动。当first的next指针为NULL时,sec即指向了要删除节点的前一个节点,接着让first指向的next指针指向要删除节点的下一个节点即可。注意如果要删除的节点是首节点,那么first向后移动结束时会为NULL,这样加一个判断其是否为NULL的条件,若为NULL则返回头结点的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
        """

        first = second = head
        for i in range(n):
            first = first.next
        if not first:
            return head.next
        while first.next:
            first = first.next
            second = second.next
        second.next = second.next.next
        return head

猜你喜欢

转载自blog.csdn.net/u014135752/article/details/80686244
今日推荐