Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

19. Remove Nth Node From End of List. Java #118

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Java/src/net/kenyang/algorithm/RemoveTheNthNodeFromList.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
public class RemoveTheNthNodeFromList {

/**
* Definition for singly-linked list.
* 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; }
* }
*/
public void remove_curr_node(ListNode node){
if (node.next != null)
node.next = node.next.next;
}
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode beforeList = new ListNode(0);
beforeList.next = head;
int size = 0;
head = beforeList;
ListNode tail = beforeList;
while (size < n) {
head = head.next;
size ++;
}
while (head.next != null) {
head = head.next;
tail = tail.next;
}
remove_curr_node(tail);
return beforeList.next;
}
}