链表的中间结点
描述给定一个带有头结点 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; } };
标签:结点,ListNode,head,链表,中间,nodesum,null
From: https://www.cnblogs.com/Huae/p/17254994.html