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

题目:

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.
   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

题意:给定一个链表,删除倒数第n个节点,返回首节点

分析:刚开始想复杂了,想着要计算出是正数第几个节点,其实不必。还是用双指针,往后走就可以了,走完一遍就找出来了。详细看代码吧。

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *p1 = head, *p2 = head;
        for(int i = 0; i < n; ++i)
            p1 = p1->next;
        if(p1 == NULL) return head->next;
        while (p1->next != NULL) {
            p1 = p1->next;
            p2 = p2->next;
        }
        p2->next = p2->next->next;
        return head;
    }
};

欢迎留言