1. 程式人生 > >劍指offer14-輸入一個連結串列,輸出該連結串列中倒數第k個結點

劍指offer14-輸入一個連結串列,輸出該連結串列中倒數第k個結點

package JZoffertest;

import JZoffertest.test3.ListNode;

public class test14a {
	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;
		
	}
	

}
package JZoffertest;

import java.util.Stack;

import JZoffertest.test3.ListNode;

public class test14 {
	
	 public ListNode FindKthToTail(ListNode head,int k) {
		 if(head==null||k<=0) {
			 return null;
		 }
		
		//先將連結串列翻轉,再列印第k個
		 Stack<ListNode> stack=new Stack<ListNode>();
		 int count=0;
		while(head!=null) {
			stack.push(head);
			head=head.next;
			count++;
		}
		if(count<k) {
			return null;
		}
		ListNode knode=null;
		for(int i=0;i<k;i++) {
			knode=stack.pop();
		}
		return knode;   
	    }
}