C++遍历一遍求出单链表中间节点的方法

题目:给出一个单链表,不知道节点N的值,怎样只遍历一次就可以求出中间节点,写出算法。

解析:设立两个指针,比如*p和*q。p每次移动两个位置,即p=p->next->next,q每次移动一个位置,即q=q->next。

当p到达最后一个节点时候,q就是中间节点了。

类似的可以用一次遍历方法得到三分之一、四分之一、前几个节点。

代码贴出:

 
 
  1. #include <iostream>
  2. using namespace std;
  3. typedef struct Student{
  4. int data;
  5. struct Student *next;
  6. }Node;
  7. /*
  8. * 遍历一遍就得到单链表的中间结点的方法
  9. * 思想:两个指针,一个每次走一步,另一个每次走两步,两步走完的时候,一步的就是结果
  10. */
  11. int getCenterNode(Node *head){
  12. Node *p2 = head;
  13. Node *p1 = head;
  14. while(p2->next!=NULL && p2->next->next!=NULL){
  15. p2 = p2->next->next;
  16. p1 = p1->next;
  17. }
  18. return p1->data;
  19. }
  20. void displayList(Node *head){
  21. cout<<"List:"<<endl;
  22. Node *p = head->next;
  23. while(p!=NULL){
  24. cout<<p->data<<" ";
  25. p=p->next;
  26. }
  27. cout<<endl;
  28. }
  29. void main(){
  30. Node *head,*tmp;
  31. int i=0;
  32. head = (Node*)malloc(sizeof(Student));
  33. head->next = NULL;
  34. for(i=0;i<10;++i){
  35. tmp = (Node*)malloc(sizeof(Student));
  36. tmp->data = i;
  37. tmp->next = head->next;
  38. head->next = tmp;
  39. }
  40. displayList(head);
  41. cout<<getCenterNode(head)<<endl;
  42. system("pause");
  43. }

转载于:https://www.cnblogs.com/alionxd/articles/3015191.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值