剑指offer之打印链表的倒数第N个节点的值

举报
chenyu 发表于 2021/07/27 01:52:45 2021/07/27
【摘要】 1 问题 打印链表的倒数第N个节点的值,(要求能只能便利链表一次) 比如链表如下,打印倒数第三个值就是4 1-> 2-> 3-> 4-> 5-> 6               2 思路 既然只要只能遍历一次,我们可以这样思考,比如我...

1 问题

打印链表的倒数第N个节点的值,(要求能只能便利链表一次)

比如链表如下,打印倒数第三个值就是4

1-> 2-> 3-> 4-> 5-> 6

 

 

 

 

 

 

 

2 思路

既然只要只能遍历一次,我们可以这样思考,比如我们要得到倒数第三个,那么它和尾巴的长度就是3,我们可以这一节距离一直往左边移动,那么移动最左边的话,他们的开始是1,尾巴是3,所以我们搞2个指针进行移动就行,如下过程,就可以得到4.

1   ->   2   ->   3   ->   4   ->   5  ->  6 

start

end    

 

1   ->   2   ->   3   ->   4   ->   5  ->  6 

start               end

 

1   ->   2   ->   3   ->   4   ->   5  ->  6 

                                start              end

无非就是上面的逆过程,我们用代码实现就行

 

 

 

 

 

 

3 代码实现


  
  1. #include <iostream>
  2. using namespace std;
  3. typedef struct node
  4. {
  5. int value;
  6. struct node *next;
  7. } Node;
  8. void printN(Node *head, int n)
  9. {
  10. if (head == NULL || n <= 0)
  11. {
  12. std::cout << "head is NULL or n <= 0" << std::endl;
  13. return;
  14. }
  15. Node *start = head;
  16. Node *end = head;
  17. //这里需要考虑n的大小长度是否大于链表长度
  18. //我们不能直接遍历链表得到链表大小然后和n比较
  19. //那我们就用start->next != NULL来判断也行
  20. for (int i = 0; i < n - 1; ++i)
  21. {
  22. if (start->next != NULL)
  23. start = start->next;
  24. else
  25. {
  26. std::cout << "the value of n is more than larger the length of list" << std::endl;
  27. return;
  28. }
  29. }
  30. while (start->next != NULL)
  31. {
  32. end = end->next;
  33. start = start->next;
  34. }
  35. std::cout << "the value is: " << end->value << std::endl;
  36. }
  37. int main()
  38. {
  39. Node *head = NULL;
  40. Node *node1 = NULL;
  41. Node *node2 = NULL;
  42. Node *node3 = NULL;
  43. head = (struct node*)malloc(sizeof(Node));
  44. node1 = (struct node*)malloc(sizeof(Node));
  45. node2 = (struct node*)malloc(sizeof(Node));
  46. node3 = (struct node*)malloc(sizeof(Node));
  47. if (head == NULL || node1 == NULL || node2 == NULL || node3 == NULL)
  48. {
  49. std::cout << "malloc fail" << std::endl;
  50. return -1;
  51. }
  52. head->value = 0;
  53. head->next = node1;
  54. node1->value = 1;
  55. node1->next = node2;
  56. node2->value = 2;
  57. node2->next = node3;
  58. node3->value = 3;
  59. node3->next = NULL;
  60. printN(head, 3);
  61. free(head);
  62. free(node1);
  63. free(node2);
  64. free(node3);
  65. return 0;
  66. }

 

 

 

 

4 运行结果

the value is: 1
 

 

 

 

 

 

 

 

5 总结

请记住,2个指针像一把梭子,那样在移动,是那么的美妙,所以当一个指针便利不了的时候,要记得用2个指针便利

然后还有类似的问题,比如求链表的中点,链表长度是奇数的时候,取中间的数字,如果链表长度是偶数的话,取中间的2个都行,我们依然用2个指针,一个走一步,一个走2步,当快的走完了的时候,慢的的走到中间了,切记。

文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。

原文链接:chenyu.blog.csdn.net/article/details/87480975

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。