LeetCode Remove Nth Node From End of List

class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        if (head == NULL) return NULL;
        ListNode* pre = NULL;
        ListNode* cur = head;
        ListNode* fast= cur;
        
        for (int i=1; i<n; i++) {
            fast = fast->next;
        }
        
        while (fast->next != NULL) {
            pre = cur;
            cur = cur->next;
            fast= fast->next;
        }
        
        if (pre == NULL) {
            return head->next;
        } else {
            pre->next = cur->next;
            return head;
        }
    }
};

一次过呗

第二轮:

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.

 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  // 10:16
10 class Solution {
11 public:
12     ListNode *removeNthFromEnd(ListNode *head, int n) {
13         ListNode fakeHead(0);
14         fakeHead.next = head;
15         ListNode* pre = NULL;
16         ListNode* slow = &fakeHead;
17         ListNode* fast = &fakeHead;
18         
19         int k = n;
20         while (k--) {
21             fast = fast->next;
22         }
23         
24         while (fast != NULL) {
25             fast = fast->next;
26             pre = slow;
27             slow = slow->next;
28         }
29         pre->next = slow->next;
30         return fakeHead.next;
31     }
32 };
原文地址:https://www.cnblogs.com/lailailai/p/3853462.html