LeetCode算法题19:删除链表的倒数第N个节点解析

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

示例:

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

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

说明:
给定的 n 保证是有效的。

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

直接搞进阶,一趟实现,那么既然是倒数第n个,那就可以设置两个指针,前面的指针先遍历n次,然后两个指针再一起走,当第一个指针指向末尾时,那么第二个指针就指向了倒数第n个。写算法时需要注意,如果是要删除头元素,那么第一个指针最后指向了空。所以第一个指针第一次遍历之后需要判断一下,然后第二次遍历时需要判断的条件是第一指针的下一个是否为空,因为我们需要获得的不是指向倒数第n个的指针,而是其上一个。
C++源代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *first=head;
        ListNode *second=head;
        while(n--)
            first = first->next;
        if(first==NULL)
            return head->next;
        while(first->next!=NULL)
        {
            first = first->next;
            second = second->next;
        }
        second->next =  second->next->next;
        return head;
    }
};

python3源代码:

# 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
        """
        first = head
        second = head
        while n!=0:
            first = first.next
            n -= 1
        if first==None:
            return head.next
        while first.next!=None:
            first = first.next
            second = second.next
        second.next = second.next.next
        return head

猜你喜欢

转载自blog.csdn.net/x603560617/article/details/84581214