第一道
1)求单链表中有效节点的个数
2)查找单链表中的倒数第k个结点
/**
* 获取单链表的节点的个数(如果是带头结点的链表,需求不统计头节点)
*
* @param head head 链表的头节点
* @return 返回的就是有效节点的个数
*/
public static int getLength(HeroNode head) {
if (head.next == null) {
return 0;
} else {
int length = 0;
HeroNode cur = head.next;
while (cur != null) {
length++;
cur = cur.next;
}
return length;
}
}
/**
* 查找单链表中的倒数第k个结点【新浪面试题】
* 思路
* 1、编写一个方法,接收head节点,同时接收一个index
* 2、index 表示是倒数第index个节点
* 3、先把链表从头到尾遍历,得到链表的总的长度 getLength
* 4、得到size后,我们从链表的第一个开始遍历(size-index)个,就可以得到
* 5、如果找到了,则返回该节点,否则返回null
*
* @param head
* @param index
* @return
*/
public static HeroNode findLastIndexNode(HeroNode head, int index) {
if (head.next == null) {
return null;
} else {
//第一个遍历得到链表的长度(节点个数)
int size = getLength(head);
//第二次遍历 size-index 位置, 就是我们倒数的第k个节点
//先做一个index的校验
if (index > 0 && index <= size) {
//定义辅助变量,for 循环定位到倒数的index
HeroNode cur = head.next;
for(int i = 0; i < size - index; ++i) {
cur = cur.next;
}
return cur;
} else {
return null;
}
}
}