当前位置:网站首页>LeetCode-876. Middle of the Linked List

LeetCode-876. Middle of the Linked List

2022-08-10 15:35:00 51CTO


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.
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

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.
  • 1.
  • 2.
  • 3.

 

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;
}
};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

 

LeetCode-876. Middle of the Linked List_o

原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://blog.51cto.com/u_14150327/5564021