最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

CrackingtheCodingInterviewQ2.2

来源:动视网 责编:小采 时间:2020-11-09 08:32:12
文档

CrackingtheCodingInterviewQ2.2

CrackingtheCodingInterviewQ2.2:题干如下: /* Instruction: Implement an algorithm to find the kth to last element of a singly linked list. */ 我用了一个private一个public函数实现。 public函数是由main函数调用,然后public的函数又调用private,这
推荐度:
导读CrackingtheCodingInterviewQ2.2:题干如下: /* 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. */ 我用了一个private一个public函数实现。 public函数是由main函数调用,然后public的函数又调用private,这主要是因为传递函数包括头指针

题干如下:

/* Instruction: Implement an algorithm to find the kth to last element of a singly linked list. */
我用了一个private+一个public函数实现。

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;
}
很直观,不需要解释,就是调用一个private函数,如下所示:

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;
}
运用recursive,不断地将current指针向后移,指向尾指针,当执行kth(tail, k, i)时,i=0,之后每执行完一个函数,则++i。当i = k时,就可以得到倒数第k个node指向的值。

另外补充一定,之所以用int& i是因为i的值要不断更新,所以每个function的i的地址都要一样,故用了引用标志&

源码如下: https://github.com/YimengL/CTCI-cpp/blob/master/2_2.cpp

文档

CrackingtheCodingInterviewQ2.2

CrackingtheCodingInterviewQ2.2:题干如下: /* Instruction: Implement an algorithm to find the kth to last element of a singly linked list. */ 我用了一个private一个public函数实现。 public函数是由main函数调用,然后public的函数又调用private,这
推荐度:
标签: the coding cra
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top