-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy path0019. Remove Nth Node From End of List.cpp
87 lines (75 loc) · 2.66 KB
/
0019. Remove Nth Node From End of 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
19.✅ Remove Nth Node From End of List
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *temp = new ListNode; //Allocating Memory For New Node using new Keyword;
temp = head; //Initializing it to head;
int cnt = 0;
while(temp != NULL)
{
cnt++;
temp = temp->next;
}
if(cnt == 0)
return head;
int cnt_first = (cnt - n) + 1; //position of nth node from head
head = Delete(head , cnt_first , cnt); //function Delete to Delete the Node
return head;
}
ListNode *Delete(ListNode *head, int pos,int cnt)
{
if(head == NULL)
return head;
//If Deleted Node happen to be first Node
else if(head != NULL && pos == 1)
{
ListNode *curr = new ListNode; //Allocating memory using keyword new & then initializing node to head
curr = head;
// ListNode *curr = head; //C syntax
head = head -> next;
// free(curr); //C syntax
delete curr;
curr = NULL;
}
//If Deleted Node happen to be Last Node
else if(head != NULL && pos == cnt )
{
ListNode *curr = new ListNode; //Allocating memory using keyword new & then initializing node to head;
curr = head;
while (curr->next->next != NULL)
{
curr = curr->next;
}
ListNode *temp = new ListNode;
temp = curr->next;
// free(temp); //C syntax
delete temp;
temp = NULL;
curr->next = NULL;
}
else if(cnt < pos || cnt < 1)
{
// cout<<"Not a valid position"<<end;
}
//If Deleted Node happen to be the Intermediate Node
else
{
ListNode *curr = new ListNode; //Allocating memory using keyword new & then initializing node to head;
curr = head;
ListNode *prev = new ListNode;
prev = head;
// ListNode *prev = NULL, *curr = head; //C syntax
while(pos > 1)
{
prev = curr;
curr = curr -> next;
pos--;
}
prev -> next = curr -> next;
// free(curr); //C syntax
delete curr;
curr = NULL;
}
return head;
}
};