[LeetCode]Remove Nth Node From End of List

又一道链表题。CareerCup上也有类似题目,trick和“部分链表逆序”一样,由于不知道链表的长度,second指针比first指针先走n步,然后在同时向前移动,直到second指针到达链表尾。注意删除头节点的情况。

假设链表长度为N,倒数第k个节点是正数第N-k个节点(k<=N),前驱指针p指向第N-k-1个节点,后向指针q指向第N个节点。

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

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.

代码

 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         // Note: The Solution object is instantiated only once and is reused by each test case.
13         if(head == NULL)
14             return head;
15             
16         ListNode *p = NULL;
17         ListNode *q = head;
18         for(int i=1; i<n; ++i)
19             q = q->next;
20         while(q->next!=NULL)
21         {
22             if(p)
23                 p = p->next;
24             else
25                 p = head;
26             q = q->next;
27         }
28         if(p)
29         {
30             ListNode *tmp = p->next;
31             p->next = tmp->next;
32             delete tmp;
33         }
34         else
35         {
36             ListNode *tmp = head;
37             head = head->next;
38             delete tmp;
39         }
40         
41         return head;
42     }
43 };

原文地址:https://www.cnblogs.com/practice/p/3382434.html