链表的中间结点

发布时间 2023-03-25 16:30:16作者: 星云体

 

链表的中间结点

 
描述

给定一个带有头结点 head 的非空单链表,返回链表的中间结点。

如果有两个中间结点,则返回第二个中间结点。

 

 
样例

样例 1:

输入:1->2->3->4->5->null
输出:3->4->5->null

样例 2:

输入:1->2->3->4->5->6->null
输出:4->5->6->null

/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param head: the head node
     * @return: the middle node
     */
    ListNode* middleNode(ListNode *head) {
        // write your code here.
        if (head == NULL)
            return NULL;
        
        int nodesum = 0;
        ListNode* pret = head;
        while( head != NULL )
        {
            nodesum ++;
            head = head->next;
        }

        nodesum = nodesum / 2 ;

        while(nodesum > 0)
        {
            pret = pret->next;
            nodesum --;
        }
        return pret;
    }

};