-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove_nth_node_from_end_of_link.cpp
More file actions
47 lines (41 loc) · 1 KB
/
remove_nth_node_from_end_of_link.cpp
File metadata and controls
47 lines (41 loc) · 1 KB
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
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: The head of linked list.
*/
ListNode *removeNthFromEnd(ListNode *head, int n) {
// write your code here
if (n <= 0) {
return head;
}
ListNode dummyNode(0);
dummyNode.next = head;
ListNode* pre_delete_node = &dummyNode;
for (int i = 0; i < n; i++) {
if (head == NULL) {
return NULL;
}
head = head->next;
}
while(head != NULL) {
head = head->next;
pre_delete_node = pre_delete_node->next;
}
pre_delete_node->next = pre_delete_node->next->next;
return dummyNode.next;
}
};