Skip to content

Commit 1951dcb

Browse files
committed
.\removeNthFromEnd.cpp
1 parent 44f4363 commit 1951dcb

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

‎LeetCode/removeNthFromEnd.cpp‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#include <iostream>
2+
#include <climits>
3+
#include <algorithm>
4+
#include <string>
5+
#include <cstring>
6+
#include <vector>
7+
using namespace std;
8+
9+
#define REP(i,n) for(int i=0;i<(n);++i)
10+
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
11+
#define RFOR(i,a,b) for(int i=(a);i>=(b);--i)
12+
typedef long long LL;
13+
14+
struct ListNode {
15+
int val;
16+
ListNode *next;
17+
ListNode(int x) : val(x), next(NULL) {}
18+
};
19+
20+
class Solution {
21+
public:
22+
ListNode *removeNthFromEnd(ListNode *head, int n) {
23+
ListNode *pre = NULL, *cur = head;
24+
REP(i,n-1) cur = cur->next;
25+
while (cur->next != NULL) {
26+
if (pre == NULL) pre = head;
27+
else pre = pre->next;
28+
cur = cur->next;
29+
}
30+
if (pre == NULL) return head->next;
31+
pre->next = pre->next->next;
32+
return head;
33+
}
34+
};
35+
36+
int main() {
37+
ListNode n1 = ListNode(1);
38+
ListNode n2 = ListNode(2);
39+
n1.next = &n2;
40+
ListNode n3 = ListNode(3);
41+
n2.next = &n3;
42+
ListNode n4 = ListNode(4);
43+
n3.next = &n4;
44+
ListNode n5 = ListNode(5);
45+
n4.next = &n5;
46+
47+
ListNode *head = &n1;
48+
49+
50+
Solution s = Solution();
51+
ListNode *res = s.removeNthFromEnd(head, 2);
52+
53+
while (res != NULL) {
54+
cout << res->val << endl;
55+
res = res->next;
56+
}
57+
58+
return 0;
59+
}

0 commit comments

Comments
 (0)