題干如下: /* Instruction: Implement an algorithm to find the kth to last element of a singly linked list. */ 我用了一個private一個public函數實現。 public函數是由main函數調用,然后public的函數又調用private,這主要是因為傳遞函數包括頭指針
題干如下:
/* Instruction: Implement an algorithm to find the kth to last element of a singly linked list. */
public函數是由main函數調用,然后public的函數又調用private,這主要是因為傳遞函數包括頭指針,而頭指針在我寫的類里面是一個private類型。
public函數如下所示:
/* find the kth to last element */ node* linkedlist::kth(int k) { int i = 0; node* result = kth(head, k, i); // cout << result->character << endl; return result; }
node* linkedlist::kth(node* head, int k, int& i) { if(head == NULL) return NULL; node* current = kth(head->next, k, i); ++i; if (i == k) { cout << head->character << endl; return head; } return current; }
另外補充一定,之所以用int& i是因為i的È要不斷更新,所以每個function的i的地址都要一樣,故用了引用標志&
源碼如下: https://github.com/YimengL/CTCI-cpp/blob/master/2_2.cpp
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com