[LeetCode] 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-1,每次两个指针向后一步,当后面一个指针没有后继了,前面一个指针就是要删除的节点。
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 // Start typing your C/C++ solution below 13 // DO NOT write int main() function 14 if (head == NULL) 15 return NULL; 16 17 ListNode *pPre = NULL; 18 ListNode *p = head; 19 ListNode *q = head; 20 for(int i = 0; i < n - 1; i++) 21 q = q->next; 22 23 while(q->next) 24 { 25 pPre = p; 26 p = p->next; 27 q = q->next; 28 } 29 30 if (pPre == NULL) 31 { 32 head = p->next; 33 delete p; 34 } 35 else 36 { 37 pPre->next = p->next; 38 delete p; 39 } 40 41 return head; 42 } 43 };