File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
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 sz = 0 ;
15
+ ListNode* tmp = head;
16
+ while (tmp != NULL ){
17
+ sz++;
18
+ tmp = tmp -> next;
19
+ }
20
+ if (sz == n){
21
+ head = head -> next;
22
+ return head;
23
+ }
24
+
25
+ tmp = head;
26
+ int curr = 0 ;
27
+ ListNode* prev = NULL ;
28
+ while (tmp != NULL ){
29
+ curr++;
30
+ int diff = sz - curr;
31
+ if (diff == n){
32
+ tmp -> next = tmp -> next -> next;
33
+ break ;
34
+ }
35
+ tmp = tmp -> next;
36
+ }
37
+ return head;
38
+ }
39
+
40
+ };
You can’t perform that action at this time.
0 commit comments