2095.删除链表的中间节点

时游小于 1 分钟LeetCode

2095.删除链表的中间节点

/*
 * @lc app=leetcode.cn id=2095 lang=typescript
 *
 * [2095] 删除链表的中间节点
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function deleteMiddle(head: ListNode | null): ListNode | null {
	if (head == null) return null;
	let len = 0;
	let current: ListNode | null = head;
	while (current) {
		current = current.next;
		len++;
	}

	let mid = Math.floor(len / 2); // 取中
	console.log(mid);
	let cur = head as ListNode;
	while (mid >= 1) {
		if (mid == 1) {
            let n = cur.next as ListNode
			cur.next = n.next;
			return head;
		}
		mid--;
		cur = cur.next as ListNode;
	}

	return null;
}
class ListNode {
	val: number;
	next: ListNode | null;
	constructor(val?: number, next?: ListNode | null) {
		this.val = val === undefined ? 0 : val;
		this.next = next === undefined ? null : next;
	}
}

let listTag1 = new ListNode(1);
let listTag2 = new ListNode(3);
let listTag3 = new ListNode(4);
let listTag4 = new ListNode(7);
let listTag5 = new ListNode(1);
let listTag6 = new ListNode(2);
let listTag7 = new ListNode(6);

listTag1.next = listTag2;
listTag2.next = listTag3;
listTag3.next = listTag3;
listTag4.next = listTag5;
listTag5.next = listTag6;
listTag6.next = listTag7;

console.log(deleteMiddle(listTag1));

// @lc code=end

上次编辑于:
贡献者: 15327360835
Loading...