打印链表的有效节点、打印链表的倒数第K个结点
打印链表的有效节点:就是链表的长度呗,从头结点开始遍历,下一个节点不是null就计数器加1
public int getLength(Node head){ Node temp = head; int length = 0; if (head.next == null){ System.out.println("链表为空"); }else { while (temp.next != null){ length++; temp = temp.next; } } return length; }
打印链表的倒数第K个结点:先算出链表长度,从头遍历 长度-K 就是第K个结点
public Node getLastK(Node head,int K){ int size = getLength(head); Node cur = head.next; if (head == null){ return null; } if (K <=0 || K > size){ return null; } for (int i = 0; i<size - K;i++){ cur = cur.next; } return cur; }
学习的博客多用于在笔记中,防止笔记过于臃肿,所以将样例及运行结果放在博客中,后以超链接的形式记录在笔记中,所以有些博文过于单薄。如果有小伙伴遇到问题欢迎评论,看到就会回复,学渣一枚,加油努力。