编程实现一个单链表建立、测长、打印。
#include <iostream> #include <stdlib.h> using namespace std; typedef struct student{ int data; struct student *next; }node; int x,cycle = 1; node* create(){ node *head,*p,*s; head = new node;//(node*)malloc(sizeof(node)); head->data = -1; p = head; return (head); } int length(node *head){ int n =-1; node *p; p = head; while(p!=NULL){ p = p->next; n++; } return n; } void print(node* head){ node* p; int n; n = length(head); cout<<"\nNOW, these "<<n<< " records are :\n"; p = head; if(head != NULL) while(p!=NULL){ cout<<"\n "<<p->data; p = p->next; } } void dellist(node *head){ node* p; while(head!=NULL){ p = head; head = head->next; cout<<"\nrecycle:"<<p->data; delete p;//free(p); } } int main(){ node* list = create(); node *p = list; node *s=NULL; while(cycle){ cout<<"\nplease input the data:"; cin>>x; if(x!=0){ s = new node;//(node*)malloc(sizeof(node)); s->data = x; s->next = NULL; cout<<"\n"<<s->data; p->next = s; p = s; } else{ cycle = 0; } } print(list); int a = length(list); cout<<"\nlength:"<<a; dellist(list); getchar(); getchar(); return 0; }
原文:http://www.cnblogs.com/yuanzhenliu/p/5308411.html