《劍指offer》11.鏈表中倒數第k個節點

題目

輸入一個鏈表,輸出該鏈表中倒數第k個結點。

思路

image

簡單思路: 循環到鏈表末尾找到 length 在找到length-k節點 需要循環兩次。

優化:設定兩個節點,間距相差k個節點,當前面的節點到達終點,取後面的節點。

前面的節點到達k後,後面的節點纔出發。

本題目着重考察代碼魯棒性、容錯率: 需要考慮head爲null,k爲0,k大於鏈表長度的情況

代碼

    function FindKthToTail(head, k) {
      if (!head || !k) return null;
      let front = head;
      let behind = head;
      let index = 1;
      while (front.next) {
        index++;
        front = front.next;
        if (index > k) {
          behind = behind.next;
        }
      }
      return (k <= index) && behind;
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章