リンクされたリストのジャンプ
3464 ワード
説明
正の整数を含む単一リンク リスト node
が与えられます.すべてのノードの next
がノード val
先のノードを指している同じリンクされたリストを返します.そのようなノードがない場合、next
は null を指す必要があります.
制約:
n ≤ 100,000
n
は node
のノード数です例1
入力
node = [2, 1, 4, 1]
出力
[2, 4]
説明
Note that 2's next is 2 node ahead. 4's next is out of bounds, so it's set to null.
直感
実装
import java.util.*;
/**
* class LLNode {
* int val;
* LLNode next;
* }
*/
class Solution {
public LLNode solve(LLNode node) {
int steps;
LLNode head = node;
while (node != null) {
steps = node.val;
for (int i = 1; i < steps; i++) {
if (node.next != null) {
node.next = node.next.next;
} else {
break;
}
}
node = node.next;
}
return head;
}
}
複雑
import java.util.*;
/**
* class LLNode {
* int val;
* LLNode next;
* }
*/
class Solution {
public LLNode solve(LLNode node) {
int steps;
LLNode head = node;
while (node != null) {
steps = node.val;
for (int i = 1; i < steps; i++) {
if (node.next != null) {
node.next = node.next.next;
} else {
break;
}
}
node = node.next;
}
return head;
}
}
複雑
Reference
この問題について(リンクされたリストのジャンプ), 我々は、より多くの情報をここで見つけました https://dev.to/jiangwenqi/linked-list-jumps-k1hテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol