求链表中第k个节点

这道题做法有很多种,首先讲一下像我这种脑子不是很好使的直白的做法。

当然是先循环求出长度,再循环找到倒数第k个节点,即整数的n-k+1。

/*
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 length = 0;
        ListNode temp = new ListNode(0);
        while(head.next!=null){
          
        }
        while(head!=null){
            if(length == k){
                return head;
            }
            length--;
            head = head.next;
        }
        return null;
    }
}

然后讲一下比较聪明的做法:

设置两个指针,一个快指针,一个慢指针。快指针先走k步,然后慢指针再开始走。当快指针到达终点时,慢指针的位置就是倒数第k个节点。其实很好理解。他们一起走的长度是n-k。即慢指针走了n-k的长度。还剩下k的长度。即是倒数第k个节点。

/*
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 length = 0;
           ListNode fast = head;
           ListNode slow = head;
           while(fast!=null){
               if(k > 0){
                   k--;
               }else{
                   slow = slow.next;
               }
               fast = fast.next;
           }
        if(k!=0)
            return null;
        return slow;
    }
}

还有一种做法其实也是比较常见的。前提是递归思想对于你已经根深蒂固。写递归的时候碰到一个奇怪的问题,cnt变量不要设置成static的。不然答案会少一个节点。比如5{1,2,3,4,5},答案会是{2,3,4,5}。至于为什么不能是静态我也说不太明白,估计和初始化顺序有关系。有大神看到,希望给出仔细的回答。

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    int cnt = 0;
    public ListNode FindKthToTail(ListNode head,int k) {
         if(null == head){
               return null;
           }
           ListNode temp = FindKthToTail(head.next,k);
           if(temp!=null){
               return temp;
           }
           cnt++;
          if(cnt == k){
              return head;
          }else{
              return null;
          }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值