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

来源:互联网 发布:阿里安全软件 编辑:程序博客网 时间:2024/05/16 06:59
#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;}

原创粉丝点击