forked from sakshamchecker/Hacktoberfest-21
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemove nth node from the end of a linked List.cpp
54 lines (49 loc) · 1.27 KB
/
Remove nth node from the end of a linked List.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution
{
public:
ListNode *removeNthFromEnd(ListNode *head, int n)
{
ListNode *fastPointer = head;
ListNode *slowPointer = head;
for (int i = 0; i < n; i++)
{
fastPointer = fastPointer->next;
}
if (fastPointer == NULL)
return head->next;
while (fastPointer->next != NULL)
{
fastPointer = fastPointer->next;
slowPointer = slowPointer->next;
}
slowPointer->next = slowPointer->next->next;
return head;
}
};
int main()
{
ListNode *head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head->next->next->next->next = new ListNode(5);
Solution s;
ListNode *result = s.removeNthFromEnd(head, 2);
while (result != NULL)
{
cout << result->val << " ";
result = result->next;
}
return 0;
}