Solution for LeetCode Problem #19 Remove Nth Node From End of List
it is linked list problem can be solved with multiple solutions, but I'm gonna solve it with fastest solution in java.
Problem link
Thank you,
AhmedG
it is linked list problem can be solved with multiple solutions, but I'm gonna solve it with fastest solution in java.
Problem link
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
public class ListNode { | |
int val; | |
ListNode next; | |
ListNode() { | |
} | |
ListNode(int val) { | |
this.val = val; | |
} | |
ListNode(int val, ListNode next) { | |
this.val = val; | |
this.next = next; | |
} | |
} |
- we should assign dummy_head it is common while solving linked list problems
- Assign 2 iterators slow and fast both equals to dummy_head
- we don't know the length of the list but we know it is always valid, so we will move with a window of size n+1 when we reach the end by the fast iterator the slow iterator will be in the node n+1 from the last, right?
- we will assign slow.next to be equal slow.next.next we are dropping the node n from last, got it?
- we will return dummy_head.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
class Solution { | |
public ListNode removeNthFromEnd(ListNode head, int n) { | |
ListNode dummy_head = new ListNode(0); | |
dummy_head.next = head; | |
ListNode fast = dummy_head; | |
ListNode slow = dummy_head; | |
for (int i= 1 ; i <= n+1; i++){ | |
fast = fast.next; | |
} | |
while(fast != null){ | |
fast = fast.next; | |
slow = slow.next; | |
} | |
slow.next = slow.next.next; | |
return dummy_head.next; | |
} | |
} |
Thank you,
AhmedG
Comments
Post a Comment