首页 > 编程语言 > 详细

C++ 链表

时间:2016-03-22 21:54:48      阅读:271      评论:0      收藏:0      [点我收藏+]

编程实现一个单链表建立、测长、打印。

技术分享
#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;
}
View Code

 

C++ 链表

原文:http://www.cnblogs.com/yuanzhenliu/p/5308411.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!