您的位置:首页 > Web前端

牛客网 剑指offer-链表中倒数第K个节点

2017-09-25 19:45 435 查看
问题描述:输入一个链表,输出该链表中倒数第k个结点。

方法一:首先遍历该链表,得其该链表的长度,然后输出链表的倒数第K个值。代码如下:

/**
* Created with IntelliJ IDEA.
* Author: 郑文华
* Date: 2017/9/25
* Time: 19:10
* public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}
}
*/

public class Solution {
public ListNode FindKthToTail(ListNode list,int k){
if(list == null)
return null;
ListNode listNode = list;
int count = 0;
while(listNode != null){
count++;
listNode = listNode.next;
}
if(count < k)
return null;
ListNode listNode1 = list;

for(int i = 0; i < count - k; i++){
listNode1 = listNode1.next;
}
return listNode1;

}
}


方法二:(最优解)两个指针,先让第一个指针和第二个指针都指向头结点,然后再让第一个指正走(k-1)步,到达第k个节点。然后两个指针同时往后移动,当第一个结点到达末尾的时候,第二个结点所在位置就是倒数第k个节点了。

public class Solution {
public ListNode FindKthToTail(ListNode list,int k){
if(list == null || k < 0)
return null;
ListNode fristNode = list;
ListNode lastNode = list;
for (int i = 1; i < k; i++) {
fristNode = fristNode.next;
}
while(fristNode != null){
fristNode = fristNode.next;
lastNode = lastNode.next;
}
return lastNode;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: