2095. 删除链表的中间节点
解题思路
- 要删除链表的中间节点 首先找到前驱节点
- 先统计链表长度 计算n / 2 -1 也就是中间节点前面一个节点
- 然后遍历链表 找到前驱节点 最后删除即可
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
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;
}
}