Skip to content

Latest commit

 

History

History
27 lines (24 loc) · 557 Bytes

求单链表节点个数.md

File metadata and controls

27 lines (24 loc) · 557 Bytes
public class ListNode {
  int num;
  ListNode next;
}

// 递归方式
public int getSingleLinkedListNodeCount(ListNode node) {
  if (node == null) return 0;
  if (node.next == null) return 1;
  return 1 + getSingleLinkedListNodeCount(node.next);
}

// 循环方式
public int getSingleLinkedListNodeCount2(ListNode node) {
    if (node == null) return 0;
    if (node.next == null) return 1;
    int sum = 1;
    ListNode tmpNode = node.next;
    while(tmpNode != null) {
        sum++;
        tmpNode = tmpNode.next;
    }
    return sum;
}