LeetCode-876. Middle of the Linked List

网友投稿 550 2022-10-02

LeetCode-876. Middle of the Linked List

LeetCode-876. Middle of the Linked List

Given a non-empty, singly linked list with head node ​​head​​, return a middle node of linked list.

If there are two middle nodes, return the second middle node.

Example 1:

Input: [1,2,3,4,5]Output: Node 3 from this list (Serialization: [3,4,5])The returned node has value 3. (The judge's serialization of this node is [3,4,5]).Note that we returned a ListNode object ans, such that:ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.

Example 2:

Input: [1,2,3,4,5,6]Output: Node 4 from this list (Serialization: [4,5,6])Since the list has two middle nodes with values 3 and 4, we return the second one.

Note:

The number of nodes in the given list will be between​​1​​​ and​​100​​.

题解:

class Solution {public: ListNode* middleNode(ListNode* head) { ListNode *p, *q; p = q = head; int n = 0; while (p != NULL) { p = p->next; n++; if (n % 2 == 0) { q = q->next; } } return q; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:小程序url不能加端口号吗(小程序配置域名端口)
下一篇:LeetCode-740. Delete and Earn
相关文章

 发表评论

暂时没有评论,来抢沙发吧~