Skip to content

Commit 51d8a19

Browse files
committed
19 remove nth node from end of list
1 parent 44855cf commit 51d8a19

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* removeNthFromEnd(ListNode* head, int n) {
14+
int cnt=0;
15+
ListNode* curr=head;
16+
while(curr){
17+
curr=curr->next;
18+
cnt++;
19+
}curr=head;
20+
if(n==1 && cnt==1)
21+
return NULL;
22+
if(cnt-n==0)
23+
return head->next;
24+
for(int i=1;i<cnt-n;i++){
25+
curr=curr->next;
26+
}
27+
if(curr->next==NULL)
28+
return head;
29+
if(curr->next->next==NULL)
30+
curr->next=NULL;
31+
else
32+
curr->next=curr->next->next;
33+
return head;
34+
}
35+
};
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<h2><a href="https://leetcode.com/problems/remove-nth-node-from-end-of-list/">19. Remove Nth Node From End of List</a></h2><h3>Medium</h3><hr><div><p>Given the <code>head</code> of a linked list, remove the <code>n<sup>th</sup></code> node from the end of the list and return its head.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong>Example 1:</strong></p>
5+
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg" style="width: 542px; height: 222px;">
6+
<pre><strong>Input:</strong> head = [1,2,3,4,5], n = 2
7+
<strong>Output:</strong> [1,2,3,5]
8+
</pre>
9+
10+
<p><strong>Example 2:</strong></p>
11+
12+
<pre><strong>Input:</strong> head = [1], n = 1
13+
<strong>Output:</strong> []
14+
</pre>
15+
16+
<p><strong>Example 3:</strong></p>
17+
18+
<pre><strong>Input:</strong> head = [1,2], n = 1
19+
<strong>Output:</strong> [1]
20+
</pre>
21+
22+
<p>&nbsp;</p>
23+
<p><strong>Constraints:</strong></p>
24+
25+
<ul>
26+
<li>The number of nodes in the list is <code>sz</code>.</li>
27+
<li><code>1 &lt;= sz &lt;= 30</code></li>
28+
<li><code>0 &lt;= Node.val &lt;= 100</code></li>
29+
<li><code>1 &lt;= n &lt;= sz</code></li>
30+
</ul>
31+
32+
<p>&nbsp;</p>
33+
<p><strong>Follow up:</strong> Could you do this in one pass?</p>
34+
</div>

0 commit comments

Comments
 (0)