/*
* @param head: The first node of linked list.
* @param n: An integer
* @return: The head of linked list.
*/
public ListNode removeNthFromEnd(ListNode head, int n) {
// write your code here
// slow is point before target, fast gonna reach the end of list
ListNode slow = head;
ListNode fast = head;
// There is n nodes between slow and fast
for (int i = 0; i < n; i++) {
fast = fast.next;
}
// Case: 1->null 1, 1->2->null 2
if(fast == null) {
head = head.next;
return head;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
if (slow == head) {
head = head.next;
} else {
slow.next = slow.next.next;
}
return head;
}
}
public class Solution { /** * @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 (head == null) { return head; } ListNode dummy = new ListNode(0); dummy.next = head; head = dummy.next; ListNode p1 = dummy; ListNode p2 = dummy; for (int i = 0; i < n; i++) { p1 = p1.next; } while (p1.next != null) { p1 = p1.next; p2 = p2.next; } p2.next = p2.next.next; return dummy.next; } }
No comments:
Post a Comment