题干如下: /* 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