1.问题描述:
计算链表中有多少个节点。
2.样例:
给出 1->3->5
, 返回 3。
3.代码:
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: head: the first node of linked list.
@return: An integer
"""
def countNodes(self, head):
# write your code here
count=0
cur=head
while cur:
count+=1
cur=cur.next
return count