您的位置:首页 > 其它

输入一个链表,输出该链表中倒数第k个结点。

2017-07-04 14:52 344 查看
public ListNode FindKthToTail1(ListNode head,int k) {
ListNode p=head;
int count = 0;
while(p!=null){
count++;
p=p.next;
}
if(k>count) return null;
ListNode p1=head;
for(int i=0;i<count-k;i++){
p1=p1.next;
}
return p1;

}


public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(k<=0)return null;
ListNode p1=head;
ListNode p2=head;
for(int i=0;i<k-1;i++){
if(p2==null)return null;
p2=p2 .next;
}
if(p2==null) return null;
while(p2.next!=null){
p1=p1.next;
p2=p2.next;
}
return p1;

}
}注意   判断链表节点数时 p!=null 因为最后一个节点包括在内,而  判断指针是否走到最后一个时 p.next!=null 因为把最后一个节点的null作为区别其他节点的标志
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐