//Given the head of a linked list, remove the nth node from the end of the list
//and return its head.
//
//
// Example 1:
//
//
//Input: head = [1,2,3,4,5], n = 2
//Output: [1,2,3,5]
//
//
// Example 2:
//
//
//Input: head = [1], n = 1
//Output: []
//
//
// Example 3:
//
//
//Input: head = [1,2], n = 1
//Output: [1]
//
//
//
// Constraints:
//
//
// The number of nodes in the list is sz.
// 1 <= sz <= 30
// 0 <= Node.val <= 100
// 1 <= n <= sz
//
//
//
// Follow up: Could you do this in one pass?
// Related Topics Linked List Two Pointers
// 👍 10475 👎 494
//leetcode submit region begin(Prohibit modification and deletion)
/**
* 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; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int listLen = 0;
ListNode temp = head;
if (head == null || n <= 0) {
return head;
}
while (temp != null) {
listLen++;
temp = temp.next;
}
if (listLen < n) {
return head;
}
if (listLen == n) {
ListNode result = head.next;
head.next = null;
return result;
}
int subLen = listLen - n - 1;
temp = head;
for (int i = 0; i < subLen; i++) {
temp = temp.next;
}
ListNode removeNode = temp.next;
temp.next = removeNode.next;
removeNode.next = null;
return head;
}
}
//leetcode submit region end(Prohibit modification and deletion)