-
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: update leetcode solutions: No.0019. Remove Nth Node From End of…
… List
- Loading branch information
Showing
5 changed files
with
163 additions
and
45 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
38 changes: 20 additions & 18 deletions
38
solution/0000-0099/0019.Remove Nth Node From End of List/Solution.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,25 +1,27 @@ | ||
/** | ||
* Definition for singly-linked list. | ||
* 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 *p, *q ; | ||
q = head ; | ||
p = head ; | ||
|
||
for (int i = 0; i < n; ++i) | ||
q = q->next ; | ||
|
||
if (!q) | ||
{ | ||
return head->next ; | ||
ListNode* dummy = new ListNode(0, head); | ||
ListNode* p = dummy; | ||
ListNode* q = dummy; | ||
while (n-- > 0) { | ||
p = p->next; | ||
} | ||
|
||
while (q->next) | ||
{ | ||
q = q->next ; | ||
p = p->next ; | ||
while (p->next != nullptr) { | ||
p = p->next; | ||
q = q->next; | ||
} | ||
|
||
p->next = p->next->next ; | ||
return head ; | ||
q->next = q->next->next; | ||
return dummy->next; | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters