0

删除链表的中间结点

 1 year ago
source link: https://stellarx.github.io/post/436451d6.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

花 风 城市

删除链表的中间结点

发表于2022-05-18|更新于2022-05-18|算法与数据结构
字数总计:192|阅读时长:1分钟|阅读量:2
  • 删除链表的中间节点
  • 给你一个链表的头节点 head 。删除 链表的 中间节点 ,并返回修改后的链表的头节点 head 。长度为 n 链表的中间节点是从头数起第 ⌊n / 2⌋ 个节点(下标从 0 开始),其中 ⌊x⌋ 表示小于或等于 x 的最大整数。
  • 还真没想到快慢指针,妙啊

Java实现

/**
* 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) {
ListNode fast = head, slow = head, pre = head;
while(fast != null && fast.next != null) {
fast = fast.next.next;
pre = slow;
slow = slow.next;
}
if(fast == head) return null;
pre.next = pre.next.next;
return head;
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK