package algorithm.linkedlist;
/**
* @Created by XDarker
* @Description 获取单链表节点的个数
* @Date 2019/10/13 16:41
*/
public class GetLinkedListNodeLength {
public static void main(String[] args) {
Node head = null;
list(head);
System.out.println("链表长度:" + getLength(head));
head = new Node(1);
System.out.println("========链表========");
list(head);
System.out.println("链表长度:" + getLength(head));
head.next = new Node(2);
System.out.println("========链表========");
list(head);
System.out.println("链表长度:" + getLength(head));
}
/**
* @param head 头结点
* @return
*/
public static int getLength(Node head){
if (head == null){
//链表为空
return 0;
}
int num = 0;
Node cur = head;
while(cur != null){
num++;
cur = cur.next;
}
return num;
}
/**
* 显示链表
*/
public static void list(Node head){
if (head == null){
System.out.println("链表为空");
return;
}
Node temp = head;
System.out.print("链表内容:");
while (temp != null){
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
}
class Node {
Node next = null;//下一个结点
int data;//结点数据
public Node(int data){
this.data = data;
}
}