Seeking list penultimate nodes K

1. The cycle COUNT traverse the list, and then use the cycle starting from the head node, loop count-k times, k is the penultimate nodes

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. Define two references, references go k front step, and then go back reference count-k step together ,, this time went to the front end of the return 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;
	}
}

 

Published 40 original articles · won praise 4 · Views 878

Guess you like

Origin blog.csdn.net/weixin_44919969/article/details/97653281