【LeetCode】19. チェーンテーブルの最後からN番目のノードを削除する【チェーンテーブル】
7377 ワード
19. N
, n , 。
:
: 1->2->3->4->5, n = 2.
, 1->2->3->5.
:
n 。
:
?
2回の遍歴は、チェーンテーブルの長さを先に遍歴し、最後から数番目のチェーンテーブルを遍歴して削除します.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy=new ListNode(0);
dummy.next=head;
int length=0;
ListNode first=head;
while(first!=null){
length++;
first=first.next;
}
length=length-n;
first=dummy;
while(length>0){
--length;
first=first.next;
}
first.next=first.next.next;
return dummy.next;
}
}
いちじ遍歴
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode first=dummy;
ListNode second=dummy;
for(int i=1;i<=n+1;i++){
first=first.next;
}
while(first!=null){
first=first.next;
second=second.next;
}
second.next=second.next.next;
return dummy.next;
}
}