42-Remove Nth Node From End of List

  1. Remove Nth Node From End of List My Submissions QuestionEditorial Solution
    Total Accepted: 106592 Total Submissions: 361392 Difficulty: Easy
    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.
Submission Details

207 / 207 test cases passed.
Status: Accepted
Runtime: 8 ms

思路:利用快慢指针,快指针先走n步,然后快指针到末尾,那么慢指针走到第n个位置的前一个位置

/**
 * 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 *pre=head,*p=head;
        for(int i=0;i<n;++i){  //先向前走n步
                if(p!=NULL)p=p->next;
                else return head; 
        }
        if(p==NULL)return head->next; //第n+1个位置为空,那么倒数第n个位置为首元素
        while(p->next){
               pre = pre->next;   //快慢指针同时走,直到快指针到达最后一个节点
               p = p->next;
        }
        pre->next = pre->next->next;//删除该节点
        return head;
    }
};
原文地址:https://www.cnblogs.com/freeopen/p/5482924.html