-
Notifications
You must be signed in to change notification settings - Fork 0
/
delete-middle-node-of-linked-list.js
109 lines (86 loc) · 2.61 KB
/
delete-middle-node-of-linked-list.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/* Delete the Middle Node of a Linked List
You are given the head of a linked list. Delete the middle node,
and return the head of the modified linked list.
The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based indexing,
where ⌊x⌋ denotes the largest integer less than or equal to x.
For n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively.
Example 1:
Input: head = [1,3,4,7,1,2,6]
Output: [1,3,4,1,2,6]
Explanation:
The above figure represents the given linked list. The indices of the nodes are written below.
Since n = 7, node 3 with value 7 is the middle node, which is marked in red.
We return the new list after removing this node.
Example 2:
Input: head = [1,2,3,4]
Output: [1,2,4]
Explanation:
The above figure represents the given linked list.
For n = 4, node 2 with value 3 is the middle node, which is marked in red.
Example 3:
Input: head = [2,1]
Output: [2]
Explanation:
The above figure represents the given linked list.
For n = 2, node 1 with value 1 is the middle node, which is marked in red.
Node 0 with value 2 is the only node remaining after removing node 1.
Constraints:
The number of nodes in the list is in the range [1, 105].
1 <= Node.val <= 105 */
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/** optimal solution
* @param {ListNode} head
* @return {ListNode}
*/
var deleteMiddle = function(head) {
let slow = head, fast = head;
let prev = null;
if(head === null || head.next === null){
return null
}
while(slow && fast && fast.next){
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = slow.next;
slow.next = null;
return head;
};
/** naive approach
* @param {ListNode} head
* @return {ListNode}
*/
var deleteMiddle = function(head) {
let nos = 0;
let counterHead = head;
while(counterHead){
counterHead = counterHead.next;
nos++;
}
if(nos <= 1){
return null;
}
if(nos === 2){
head.next = null;
return head;
}
let prev = null;
let temp = head;
nos = Math.floor(nos / 2);
while(temp && nos > 0){
prev = temp;
temp = temp.next;
nos--;
}
let nextNode = temp.next;
prev.next = nextNode;
temp.next = null;
return head;
};