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 b4087d9

Browse files
2095. Delete the Middle Node of a Linked List
1 parent 0a94f47 commit b4087d9

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
2+
3+
/**
4+
* Definition for singly-linked list.
5+
*/
6+
7+
class ListNode(_x: Int = 0, _next: ListNode = null) {
8+
var next: ListNode = _next
9+
var x: Int = _x
10+
}
11+
12+
object Solution {
13+
import scala.annotation.tailrec
14+
15+
def len(head: ListNode): Int = {
16+
@tailrec def go(node: ListNode, acc: Int): Int = {
17+
if (node.next == null) acc + 1
18+
else go(node.next, acc + 1)
19+
}
20+
go(head, 0)
21+
}
22+
23+
def deleteMiddle(head: ListNode): ListNode = {
24+
val llen = len(head)
25+
@tailrec def go(node: ListNode, curPos: Int): Unit = {
26+
if (curPos == llen / 2 - 1) {
27+
node.next = node.next.next
28+
} else go(node.next, curPos + 1)
29+
}
30+
if (head.next == null) null
31+
else {
32+
go(head, 0)
33+
head
34+
}
35+
}
36+
37+
def pprint(head: ListNode): Unit = {
38+
@tailrec def go(node: ListNode, i: Int): Unit = {
39+
print(s"[$i]=${node.x}, ")
40+
if (node.next == null) ()
41+
else go(node.next, i + 1)
42+
}
43+
44+
go(head, 0)
45+
}
46+
}
47+
48+
val list = ListNode(1)
49+
Solution.len(list)
50+
51+
Solution.pprint(list)
52+
val nl = Solution.deleteMiddle(list)
53+
Solution.pprint(nl)

0 commit comments

Comments
(0)

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