Bootstrap

2095. 删除链表的中间节点

2095. 删除链表的中间节点


题目链接:2095. 删除链表的中间节点

代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution 
{
public:
    int getLength(ListNode* head) 
    {
        ListNode* p = head;
        int len = 0;
        while (p) 
        {
            len++;
            p = p->next;
        }
        return len;
    }

    ListNode* deleteMiddle(ListNode* head) 
    {
        int len = getLength(head);
        if (len <= 1) 
        {
            return nullptr;
        }

        int mid = len / 2 + 1;
        ListNode* p = head;
        for (int i = 1; i < mid - 1; i++) 
        {
            p = p->next;
        }

        ListNode* pNext = p->next;
        p->next = pNext->next;
        delete pNext;
        return head;
    }
};
;