鏈表節點計數(入門)
阿新 • • 發佈:2017-12-22
self. pytho div elf python java clas true count
這道題沒啥好說的就是一個普通的鏈表遍歷並且計數
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
鏈表節點計數(入門)