力扣链接
题目描述
给你一个链表的头节点 head
。删除 链表的 中间节点 ,并返回修改后的链表的头节点 head
。
长度为 n
链表的中间节点是从头数起第 ⌊n / 2
⌋ 个节点(下标从 0 开始),其中 ⌊x⌋
表示小于或等于 x
的最大整数。
- 对于
n
=1
、2
、3
、4
和5
的情况,中间节点的下标分别是0
、1
、1
、2
和2
。
解题思路
- 两次遍历
- 快慢指针
代码(两次遍历
class Solution {
public ListNode deleteMiddle(ListNode head) {
ListNode tou = new ListNode(0, head);
ListNode temp = head;
int count = 0;
//得到节点个数
while (temp != null) {
count++;
temp = temp.next;
}
int avg = count / 2;
temp = tou;
for (int i = 0; i < avg; i++) {
temp = temp.next;
}
//删除节点
temp.next = temp.next.next;
return tou.next;
}
}
复杂度
- 时间复杂度: O(n)
- 空间复杂度: O(1)
代码(快慢指针)
class Solution {
public ListNode deleteMiddle(ListNode head) {
ListNode tou = new ListNode(0, head);
ListNode first = head;
ListNode second = tou;
while (first != null && first.next != null) {
first = first.next.next;
second = second.next;
}
//删除节点
second.next = second.next.next;
return tou.next;
}
}
复杂度
- 时间复杂度: O(n)
- 空间复杂度: O(1)