编程一次遍历搜索到中间节点,如果节点数为偶数,取中间两节点中前一节点

发布时间:2016-12-11 12:27:26 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"编程一次遍历搜索到中间节点,如果节点数为偶数,取中间两节点中前一节点",主要涉及到编程一次遍历搜索到中间节点,如果节点数为偶数,取中间两节点中前一节点方面的内容,对于编程一次遍历搜索到中间节点,如果节点数为偶数,取中间两节点中前一节点感兴趣的同学可以参考一下。

#include <tchar.h> #include <iostream> using namespace std; typedef struct student{ int data; struct student * next; } node; node* create() { node *head, *p, *s; int x, cycle = 1; head = (node *)malloc(sizeof(node)); p = head; while(cycle) { cout << "please input the data: "; cin >> x; cout << endl; if( x != 0) { s = (node *)malloc(sizeof(node)); s->data = x; p->next = s; p = s; } else { cycle = 0; } } p->next = NULL; head = head->next; return head; } int length(node *head) { int n = 0; node *p; p = head; while (p != NULL) { p = p->next; n++; } return n; } void print(node *head) { int n; node *p; p = head; n = length(head); cout << "There is " << n << " data in list\n" << endl; while(p != NULL) { cout << p->data << " -> "; p = p->next; } cout << endl; } node *searchmid(node *head) { node *p, *q; if(NULL == head || NULL == head->next) //排除零个节点或者一个节点的情况 return head; p = head; q = head; while(p->next != NULL && p->next->next != NULL)//需要确认下一个节点是否为空 { p = p->next->next; q = q->next; } return q; } int _tmain(int argc, _TCHAR * argv[]) { node *head, *temp; head = create(); print(head); temp = searchmid(head); cout << temp->data <<endl; return 0; }

上一篇:用yum CentOS在线安装ffmpeg
下一篇:hdu4282(单调性+二分)

相关文章

相关评论