码迷,mamicode.com
首页 > 其他好文 > 详细

链表节点计数(入门)

时间:2017-12-22 21:49:19      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:first   init   lis   int   pytho   ext   并且   body   nbsp   

这道题没啥好说的就是一个普通的链表遍历并且计数

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
        

  

 

链表节点计数(入门)

标签:first   init   lis   int   pytho   ext   并且   body   nbsp   

原文地址:http://www.cnblogs.com/KanHin/p/8087487.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!