剑指Offer--第22题 链表中倒数第k个节点

第22题 链表中倒数第k个节点

题目: 输入一个链表,输出该链表中倒数第k个结点。
我的思路 之前好像看过类似的题目,所以思路大致为,建立连个临时节点p和q,p先走k步到达第k个节点,然后q节点开始走,到p到达尾部指向空的时候,q就是倒数第k个节点。
我的low代码

public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
    if(head==null) {
           return null;
       }
       ListNode temp = head;
       head = new ListNode(-1);
       head.next = temp;
       //p比q提前走k步;
       ListNode p = head;
       ListNode q = head;
       //循环;
       for(int i=0;i<k;i++) {
           if(p.next!=null) {   // **注意这里的条件**
               p=p.next;
           }else { //链表的长度小于k,提前结束;
               return null;
           }
       }
       
       //p,q同时走,当p到达链表尾部的时候p刚好走到倒数第k个节点;
       while(p!=null) { //** 注意这里的条件**
           p=p.next;
           q = q.next;
       }
       return q;
    }

需要注意两个判断条件
优雅的代码

链接:https://www.nowcoder.com/questionTerminal/529d3ae5a407492994ad2a246518148a
来源:牛客网

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

其实思路差不多,只是我在写关于链表的时候习惯添加一个头指针。

猜你喜欢

转载自www.cnblogs.com/LynnMin/p/9275708.html