单链表——求单链表中结点的个数

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

package jxau.lyx.Link;

/**
 * 
 * @author: liyixiang
 * @data:2014-10-1
 * @题目大意:
 * 		求单链表中结点的个数
 * @主要思路:
 * 		注意链表为空的情况
 * @时间复杂度:
 * @空间复杂度:
 */
public class GetListLength {

	//结点
	private static class Node {           
		int val;           
		Node next;               
		
		public Node(int val) {               
			this.val = val;          
		}       
	}
	
	public int getListLength(Node head){
		
		//头结点为空
		if(head == null){
			return 0;
		}
		
		int len = 0;             //链表长度
		Node cur = head;      //头结点开始
		while(cur != null){
			len ++;
			cur = cur.next;      //下一个结点
		}
		
		return len;
	}
}


转载于:https://my.oschina.net/liyixiangBlog/blog/323871

你可能感兴趣的:(单链表——求单链表中结点的个数)