单链表求有效节点个数(不包含头节点)
思路:
1. 定义一个方法,接受头节点参数
2. 对链表判空,空链表返回0
3. 定义一个长度变量接收
4. 定义一个临时节点temp
5. whle循环处理
6. 返回length
代码实现
public static int getLength(Node head){
if (head.next == null){
return 0;
}
int length = 0;
Node temp = head.next;
while (temp!=null){
length++;
temp = temp.next;
}
return length;
}
查找单链表的倒数第k个节点
思路分析:
1. 写方法 接受参数 head头节点,k 倒数第k个节点
2. 调用上面不包含头节点的有效个数 使用size接收
3. 第一个开始遍历 遍历size-k个
4. 找到返回该节点,找不到返回空
代码实现
public static Node findLastK(Node head,int k){
if (head.next == null){
return null;
}
int size = getLength(head);
if (k<=0 || k>size){
return null;
}
Node temp = head.next;
for (int i = 0; i < size-k; i++) {
temp = temp.next;
}
return temp;
}
public static int getLength(Node head){
if (head.next == null){
return 0;
}
int length = 0;
Node temp = head.next;
while (temp!=null){
length++;
temp = temp.next;
}
return length;
}