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

java 輸入一個連結串列,輸出該連結串列中倒數第k個結點。

輸入一個連結串列,輸出該連結串列中倒數第k個結點。

解題思路:

1、當輸入的連結串列為空的時候直接返回空

2、當輸入的k值大於連結串列的節點數的時候直接返回null;

3、先遍歷連結串列得出連結串列的節點數,(注意;因為後面需要重新遍歷連結串列查到倒數第k個節點,需要重新定義一個節點來保留head節點)

4、用節點數減去k就是連結串列的第幾個節點,重新遍歷連結串列找到節點返回

public class Solution {
		public ListNode FindKthToTail(ListNode head, int k) {
			if(head==null){
				return null;
			}
			int count=1;
			ListNode old=head;
			while(head.next!=null){
				head=head.next;
				count++;
			}
			if(k>count){
				return null;
			}
			for(int i=0;i<count-k;i++){
				old=old.next;
			}
			return old;
		}
	}