求链表的倒数第K个结点

1.循环遍历链表count,然后再利用循环从头结点出发,循环count-k次,即为倒数第k个结点

public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
		int count=0;
		ListNode node=head;
		for(ListNode cur=head;cur!=null;cur=cur.next)
			count++;
		if(count>k){
			for(int i=0;i<(count-k);i++)
				node=node.next;
		}
		return node;
	}
}//查找链表中倒数第k个结点

2.定义两个引用,front引用先走k步,然后在和back引用一起走count-k步,,此时front走到了结尾返回back

public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
		ListNode front=head;
		ListNode back=head;
		for(int i=0;i<k;i++){
			if(front==null)
				return null;//链表结点数小于k
			front=front.next;
                }  //front走了k步      
		while(front!=null)
		{
			front=front.next;
			back=back.next;
		}//一起走count-k步
		return back;
	}
}
发布了40 篇原创文章 · 获赞 4 · 访问量 878

猜你喜欢

转载自blog.csdn.net/weixin_44919969/article/details/97653281