Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7868ce8

Browse files
committed
feat: add question #09
1 parent 1f1776a commit 7868ce8

File tree

3 files changed

+89
-0
lines changed

3 files changed

+89
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.hi.dhl.algorithms.leetcode._019.java;
2+
3+
/**
4+
* <pre>
5+
* author: dhl
6+
* date : 2022年4月15日
7+
* desc :
8+
* </pre>
9+
*/
10+
11+
import com.hi.dhl.algorithms.model.ListNode;
12+
13+
/**
14+
* Definition for singly-linked list.
15+
* public class ListNode {
16+
* int val;
17+
* ListNode next;
18+
* ListNode() {}
19+
* ListNode(int val) { this.val = val; }
20+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
21+
* }
22+
*/
23+
class Solution {
24+
public ListNode removeNthFromEnd(ListNode head, int n) {
25+
if (head == null) {
26+
return head;
27+
}
28+
29+
ListNode dummyHead = new ListNode(0, head); // 构建一个伪节点
30+
ListNode p1 = dummyHead;
31+
ListNode p2 = head;
32+
while (n-- != 0) {
33+
p2 = p2.next;
34+
}
35+
while (p2 != null) {
36+
p1 = p1.next;
37+
p2 = p2.next;
38+
}
39+
p1.next = p1.next.next;
40+
return dummyHead.next;
41+
}
42+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.hi.dhl.algorithms.leetcode._019.kotlin
2+
3+
import com.hi.dhl.algorithms.model.ListNode
4+
5+
/**
6+
* <pre>
7+
* author: dhl
8+
* date : 2022年4月17日
9+
* desc :
10+
* </pre>
11+
*/
12+
/**
13+
* Example:
14+
* var li = ListNode(5)
15+
* var v = li.`val`
16+
* Definition for singly-linked list.
17+
* class ListNode(var `val`: Int) {
18+
* var next: ListNode? = null
19+
* }
20+
*/
21+
class Solution {
22+
fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? {
23+
if (head == null) {
24+
return head;
25+
}
26+
val dummyHead = ListNode(n, head);
27+
var p1 = dummyHead;
28+
var p2 = head;
29+
var m = n;
30+
while (m-- != 0) {
31+
p2 = p2?.next;
32+
}
33+
34+
while (p2 != null) {
35+
p1 = p1.next;
36+
p2 = p2.next;
37+
}
38+
39+
p1.next = p1.next?.next;
40+
return dummyHead.next;
41+
}
42+
}

‎00-code(源代码)/src/com/hi/dhl/algorithms/model/ListNode.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,9 @@ public class ListNode {
1414
public ListNode(int x) {
1515
val = x;
1616
}
17+
18+
public ListNode(int val, ListNode next) {
19+
this.val = val;
20+
this.next = next;
21+
}
1722
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /