Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit a3eda4f

Browse files
authoredDec 5, 2021
Create 2095-delete-the-middle-node-of-a-linked-list.js
1 parent 71fda8b commit a3eda4f

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} head
10+
* @return {ListNode}
11+
*/
12+
const deleteMiddle = function(head) {
13+
if(head == null) return head
14+
const dummy = new ListNode(null, head)
15+
let n = 0, cur = head
16+
while(cur) {
17+
n++
18+
cur = cur.next
19+
}
20+
if(n === 1) return null
21+
const mid = Math.floor(n / 2)
22+
cur = dummy.next
23+
let pre = dummy
24+
for(let i = 0; i < n; i++) {
25+
if(i === mid - 1) {
26+
pre = cur
27+
// pre.next = cur.next.next
28+
}
29+
if(i === mid) {
30+
pre.next = cur.next
31+
}
32+
if(i > mid) break
33+
cur = cur.next
34+
}
35+
return dummy.next
36+
};

0 commit comments

Comments
 (0)
Please sign in to comment.