题目:输入一个链表,输出该链表中倒数第k个结点。
思路一:遍历2次链表,第一次求出链表的长度,第二次求倒数第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) {
if(head==null)
return null;
ListNode head1=head;
int i=0;
while(head1.next!=null){
i++;
head1=head1.next;
}
if(k>i+1)
return null;
int j;
for(j=0;j<i-k+1;j++)
head=head.next;
return head;
}
}
js:
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function FindKthToTail(head, k)
{
if(head==null)
return null;
var head1=head;
var i=0;
while(head1.next!=null){
head1=head1.next;
i++;
}
if(k>i+1)
return null;
var j=0;
for(j=0;j<i-k+1;j++)
head=head.next;
return head;
// write code here
}
思路二:定义head1=head,然后将head1移动k个位置,然后将Head和Head1同时移动,当head1到了末尾时,此时的Head所指的结点就是倒数第k个结点。但是要注意特殊情况,比如k=0或者head为空等等特殊情况。
代码:
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function FindKthToTail(head, k)
{
if(head==null)
return null;
if(k==0)//注意倒数第0个,我没有考虑到
return 0;
var head1=head;
var i=0;
for(i=0;i<k-1;i++){
if(head1.next==null)
return null;
head1=head1.next;
}
while(head1.next!=null){
head1=head1.next;
head=head.next;
}
return head;
// write code here
}