美文网首页
14、链表中倒数第k个节点

14、链表中倒数第k个节点

作者: quiterr | 来源:发表于2017-09-02 21:41 被阅读0次

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

public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        ListNode p1 = null;
        ListNode p2 = null;
        
        // 使p1指向第k个节点
        while(k>0){
            if(p1==null){
                p1=head;
            }else{
                p1=p1.next;
            }
            k--;
        }
        
        //p1、p2同时向前推进,直到p1到达尾部
        while(p1!=null){
            if(p2==null){
                p2=head;
            }else{
                p2=p2.next;
            }
            p1=p1.next;
        }
        
        return p2;
    }
}

第二次做:

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

相关文章

网友评论

      本文标题:14、链表中倒数第k个节点

      本文链接:https://www.haomeiwen.com/subject/erzzittx.html