LeetCodeチェーンテーブルから最後からN番目のノードを削除
単一チェーンテーブルから最後からN番目のノードを削除し、チェーンテーブルを1回巡回するように要求します.
例は次のとおりです.
Javaバージョン、
例は次のとおりです.
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Javaバージョン、
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(null == head || n <= 0) return head;
ListNode myhead = head, tail = head;
while(n > 0 && tail.next != null){
tail = tail.next;
n--;
}
if(n > 1) return head;//n > sizeOfList
if(n == 1 && tail.next == null) return head.next;
while(tail.next != null ){
myhead = myhead.next;
tail = tail.next;
}
myhead.next = myhead.next.next;
return head;
}
}