2095. Delete the middle node of the linked list
problem solving ideas
- To delete the intermediate node of the linked list, first find the predecessor node
- First count the length of the linked list and calculate n / 2 -1, which is the node before the middle node
- Then traverse the linked list to find the predecessor node and delete it at last
class Solution {
public ListNode deleteMiddle(ListNode head) {
int count = 0;
ListNode cur = head;
while(cur != null){
count++;
cur = cur.next;
}
if(count == 1){
return null;
}
if(count == 2){
head.next = null;
return head;
}
cur = head;
int x = count / 2 - 1;
while(x-- > 0){
cur = cur.next;
}
cur.next = cur.next.next;
return head;
}
}