链表--求倒数第k个结点

求倒数第k个结点
方法1:先求长度,然后再减去k,再重新遍历
          特殊性:链表长度 == k 或者 <k 的时候

//求倒数第K个结点
 public ListNode FindKthToTail(ListNode head,int k){
  int length=0;
  for(ListNode cur=head;cur!=null;cur=cur.next){
   length++;
  }
  if(length<k){
   return null;
  }
  int n=length-k;
  ListNode kth=head;
  for(int i=0;i<n;i++){
   kth=kth.next;
  }
  return kth;
 }

测试代码

//方法2 双引用遍历
 public ListNode FindKthToTail2(ListNode head,int k){
  ListNode front=head;
  ListNode back=head;
  for(int i=0;i<k;i++){
   if(front==null){
    return null;
   }
   front=front.next;
  }
  while(front!=null){
   front=front.next;
   back=back.next;
  }
  return back;
 }
}

方法2:双引用遍历
         以我的理解,就是让一个先走相差的步数,再两个引用同时遍历,使得慢引用刚好到所求位置
个人理解的图在这里插入图片描述

//方法2 双引用遍历
 public ListNode FindKthToTail2(ListNode head,int k){
  ListNode front=head;
  ListNode back=head;
  for(int i=0;i<k;i++){
   if(front==null){
    return null;
   }
   front=front.next;
  }
  while(front!=null){
   front=front.next;
   back=back.next;
  }
  return back;
 }
}

测试代码

public static void testFindKthToTail2(){
  System.out.println("测试倒数第k个元素");
  
  ListNode n1=new ListNode(1);
  ListNode n2=new ListNode(2);
  ListNode n3=new ListNode(3);
  ListNode n4=new ListNode(4);
  ListNode n5=new ListNode(5);
  n1.next=n2;
  n2.next=n3;
  n3.next=n4;
  n4.next=n5;
  n5.next=null;
  
  Solution s=new Solution();
  ListNode result=s.FindKthToTail2(n1,5);
  display1(result);
 }

结果如下

测试倒数第k个元素
(1)
测试倒数第k个元素
(1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值