这道题没啥好说的就是一个普通的链表遍历并且计数
Java:
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /* * @param head: the first node of linked list. * @return: An integer */ public int countNodes(ListNode head) { int i = 0; while(head!=null && ++i>0) head = head.next; return i; } }
"""
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):
i = 0
while head is not None:
head = head.next
i = i+1
return i