diff options
author | Michael Hunteman <michael@michaelted.xyz> | 2022-09-22 10:14:04 -0500 |
---|---|---|
committer | Michael Hunteman <michael@michaelted.xyz> | 2022-09-22 10:14:04 -0500 |
commit | 6522012065712fb0ece31bff9ff10b38a83b10e1 (patch) | |
tree | 743f3c13d08be9f60bad57b74e7a1fe7cc675e89 /RemoveNthNode.java |
Initial commit
Diffstat (limited to 'RemoveNthNode.java')
-rw-r--r-- | RemoveNthNode.java | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/RemoveNthNode.java b/RemoveNthNode.java new file mode 100644 index 0000000..bdcde30 --- /dev/null +++ b/RemoveNthNode.java @@ -0,0 +1,37 @@ +import java.lang.*; +import java.util.*; +import node.*; + +class RemoveNthNode { + public static ListNode removeNthFromEnd(ListNode head, int n) { + if (head.next == null && n == 1) + return head.next; + + ListNode prev = head; + ListNode end = head; + while (n > 0 && end.next != null) { + end = end.next; + n--; + } + while (end.next != null) { + prev = prev.next; + end = end.next; + } + prev.next = prev.next.next; + return head; + } + + public static void main(String[] args) { + ListNode fourth = new ListNode(5, null); + ListNode third = new ListNode(4, fourth); + ListNode second = new ListNode(3, third); + ListNode first = new ListNode(2, second); + ListNode head = new ListNode(1, first); + + ListNode curr = removeNthFromEnd(head, 1); + while (curr != null) { + System.out.println(curr.val); + curr = curr.next; + } + } +} |