[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 };


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM