leetcodeチェーンテーブル問題--チェーンテーブルの最後からN番目のノードを削除します(java実装)
1580 ワード
原題
チェーンテーブルが与えられ、チェーンテーブルの最後からn番目のノードが削除され、チェーンテーブルのヘッダノードが返される.
例:
説明:
与えられたn保証は有効である.
ステップ:
スキャンを使って実現してみてもいいですか?
コード:
IDE自己測定コードを提供します.
チェーンテーブルが与えられ、チェーンテーブルの最後からn番目のノードが削除され、チェーンテーブルのヘッダノードが返される.
例:
: 1->2->3->4->5, n = 2.
, 1->2->3->5.
説明:
与えられたn保証は有効である.
ステップ:
スキャンを使って実現してみてもいいですか?
コード:
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode f = head;
ListNode s = head;
for (int i = 0; i < n; i++) {
f = f.next;
}
if(f == null) {
return head = head.next;
}
while(f.next!=null) {
f = f.next;
s = s.next;
}
s.next = s.next.next;
return head;
}
}
IDE自己測定コードを提供します.
import org.junit.Test;
public class SolutionTest {
/**
* N
*/
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode f = head;
ListNode s = head;
for (int i = 0; i < n; i++) {
f = f.next;
}
if(f == null) {
return head = head.next;
}
while(f.next!=null) {
f = f.next;
s = s.next;
}
s.next = s.next.next;
return head;
}
/**
*
*/
public static void printList(ListNode head){
if(null == head){
return;
}
while(head.next!=null) {
System.out.print(head.val+"->");
head = head.next;
}
System.out.println(head.val);
}
@Test
public void listTest(){
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
head = removeNthFromEnd(head, 3);
printList(head);
}
}