链表中倒数第k个结点
问题描述:找到链表中倒数第k个结点
首先考察基本功,正常的方法只需要遍历两次链表,第一次获得链表的长度,第二次找到链表的第K个节点就可以了,这里就不赘述了。这里就提供一个只遍历一次的做法
本方法思想:用两个指针,一个先遍历k-1个点,然后两个一块遍历,最终当前面的遍历完以后,第二个就是倒数第K个节点
持续更新...
代码附下
Java实现:
package 链表中倒数第k个结点;
/**
* 用两个指针,一个先遍历k-1个点,然后一块遍历
* 最终就是倒数第K个
* @author user
*
*/
class ListNode {
int val;
ListNode next = null;
public ListNode(int val) {
this.val = val;
}
}
public class Test {
public static void main(String[] args) {
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(3);
ListNode n4 = new ListNode(4);
ListNode n5 = new ListNode(5);
ListNode n6 = new ListNode(6);
ListNode n7 = new ListNode(7);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = n6;
n6.next = n7;
ListNode find = findLastK(n1, 8);
System.out.println(find.val);
}
public static ListNode findLastK(ListNode head, int k) {
if (k < 1 || head == null) {
return null;
}
ListNode first = head;
ListNode second = head;
for (int i = 1; i <= k - 1; i++) {
if (first.next != null) {
first = first.next;
} else {
System.out.println("k太大了");
return null;
}
}
while (first.next != null) {
first = first.next;
second = second.next;
}
return second;
}
}
持续更新...欢迎赞赏!![](https://i-blog.csdnimg.cn/blog_migrate/ca0cc5c488ad24501c0bbddad6302b17.png)
主页:https://blog.csdn.net/ustcer_93lk/article/details/80374008
https://blog.csdn.net/ustcer_93lk/article/details/80373108
如果有问题,欢迎大家留言,有更好的方法也期待大家告知。