编程实现单链表的逆置

来源:互联网 发布:单片机串口 编辑:程序博客网 时间:2024/05/19 23:57
#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 *reverse(node *head){node *p1, *p2, *p3;if(NULL == head && NULL == head->next)return head;p1 = head;p2 = p1->next;while(p2){p3 = p2->next;p2->next = p1;p1 = p2;p2 = p3;}head->next = NULL;head = p1;return head;}int _tmain(int argc, _TCHAR * argv[]){node *head;head = create();print(head);head = reverse(head);print(head);return 0;}

原创粉丝点击