Leetcode第十九题:删除链表的倒数第N个结点

题目:

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

示例:

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

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

给定的 n 保证是有效的。

进阶:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

个人思路:

双指针,So easy~

官方答案推荐:

跟我一样。

python代码:

# 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:
        node1 = head
        for _ in range(n):
            node1 = node1.next
        if node1 == None:
            head = head.next
        else:
            node2 = head
            while node1.next:
                node1 = node1.next
                node2 = node2.next
            node2.next = node2.next.next
        return head

反思:

So easy~不过考虑特殊情况不周全。。。写错了好几次

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章