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

    示例:

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

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

    给定的 n 保证是有效的。

    进阶:

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

    分析:删除链表中倒数第K个节点的问题在于找到倒数第k个节点; 方法:设置两个指针front, behind,front从head开始向前走k步后,behind从head开始与front一起向前移动,当front到达尾节点的时候,behind与front相隔K,此时behind指向的就是倒数第k个节点。 边界1:k等于链表长度时候,front移动到了尾节点,直接返回head->next;

    1. /**
    2. * Definition for singly-linked list.
    3. * struct ListNode {
    4. * int val;
    5. * ListNode *next;
    6. * ListNode(int x) : val(x), next(NULL) {}
    7. * };
    8. */
    9. class Solution {
    10. public:
    11. ListNode* removeNthFromEnd(ListNode* head, int n)
    12. {
    13. if (!head) return head;
    14. ListNode * front = head;
    15. ListNode * behind = head;
    16. while(n--) // n有效的前提下
    17. {
    18. front = front->next;
    19. }
    20. if (front == nullptr)
    21. {
    22. head = head->next;
    23. return head;
    24. }
    25. while(front->next != nullptr)
    26. {
    27. front = front->next;
    28. behind = behind->next;
    29. }
    30. behind->next = behind->next->next;
    31. return head;
    32. }

    欢迎交流,批评指正!