第十三题:输入一个链表,输出该链表中倒数第k个结点。
思路:Python版的思路是直接使用列表的倒序索引res[-k],Java版的思路是使用快慢指针,首先获得链表的长度,判断k值是否在1-链表长度之间,然后定义快慢指针均从链表头结点开始,快指针先走k-1步,当快指针到达链表末端时,慢指针正好指向倒数第k个节点。
Python:
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindKthToTail(self, head, k):
# write code here
res = []
while head != None:
res.append(head)
head = head.next
if k <= 0 or k > len(res):
return None
return res[-k]
Java:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
//长度变量
int len = 0;
//定义获取长度用的链表节点副本,以保持输入链表头结点不变
ListNode len_head = head;
//获取链表长度
while(len_head != null){
len++;
len_head = len_head.next;
}
//判断输入k值是否满足要求
if(k<=0 || k>len){
return null;
}
//定义快指针,指向链表头结点
ListNode fast_p = head;
//定义慢指针,指向链表头结点
ListNode slow_p = head;
//让快指针先移动k-1步
for(int i=1;i<k;i++){
fast_p = fast_p.next;
}
//快慢指针一起移动
while(fast_p.next != null)
{
slow_p = slow_p.next;
fast_p = fast_p.next;
}
return slow_p;
}
}
Java方法2:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
private ListNode rel;
public ListNode FindKthToTail(ListNode head,int k) {
//排除特殊情况
if(head == null){
return null;
}
helper(head, k);
return rel;
}
public int helper(ListNode head, int k){
int num = 1;
//递归到最后一个节点
if(head.next == null){
if(k == num)//若k等于1,则结果为最后一个节点
rel = head;
return num;
}
//否则,当前节点对应的num是其后续节点递归结果+1
num += helper(head.next, k);
if(k == num)
rel = head;//若当前节点对应的num等于k值,则结果为当前节点
return num;
}
}