美文网首页
leetcode--19--删除链表的倒数第N个节点

leetcode--19--删除链表的倒数第N个节点

作者: minningl | 来源:发表于2020-04-19 17:58 被阅读0次

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

示例:

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

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

说明:

给定的 n 保证是有效的。

进阶:

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

链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list

思路:
1、使用快慢两个指针指向链表的头结点。快指针先走n步,然后两个指针同时往前走直到快指针走到头

Python代码:

# 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
        """
        slow = head
        fast = head

        while n:
            fast = fast.next
            n -= 1
        if not fast:
            return head.next

        while fast.next:
            slow = slow.next
            fast = fast.next
        slow.next = slow.next.next
        return head

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* slow = head;
        ListNode* fast = head;

        while(n>0){
            fast = fast->next;
            n -= 1;
        }
        if (fast == nullptr){
            return head->next;
        }
        while(fast->next){
            fast = fast->next;
            slow = slow->next;
        }
        slow->next = slow->next->next;
        return head;
    }
};

相关文章

网友评论

      本文标题:leetcode--19--删除链表的倒数第N个节点

      本文链接:https://www.haomeiwen.com/subject/zhzvbhtx.html