題目:輸入一個鏈表,輸出該鏈表中倒數第k個結點。
這裏給出了兩種方法:
方法一
廢話不多說,先看思維邏輯圖:
當你能把下面這幅思維邏輯圖能夠很好的理解時,那麼下面的代碼也就很好理解了。
程序如下:
public ListNode findKthToTail1(int k){
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(k <=0 ||k > getLength(head)) {
return null;
//判斷k是否合理
}
ListNode fast = head;
ListNode slow = head;
while(k-1>0) {
fast = fast.next;
k--;
}
while(fast.next != null) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
public int getLength(ListNode head) {
int count = 0;
ListNode cur = head;
while(cur!= null) {
count++;
cur = cur.next;
}
return count;
}
}
}
但是這段代碼若想運行成功,還需要你單獨寫一個getLength()函數,不方便
方法二
其實這個方法與方法一大同小異(思維邏輯圖同上),較上一段代碼優化了一下,省去了寫getLength()函數,我們簡單來看一下即可。
直接上代碼:
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(k <=0||head == null ) {
return null;
}
ListNode fast = head;
ListNode slow = head;
while(k-1>0) {
if(fast.next != null){
fast = fast.next;
k--;
}else {
System.out.println("沒有這個節點");
return null;
}
}
while(fast.next != null) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
}