单链表 类

利用类的形式,动态建立Node链表:

#include<iostream>
using namespace std;
class Node
{
/*
private:
    double x_;
    double y_;
    Node   *Node_;
*/
public:
    double x_;
    double y_;
    Node   *Node_;    //定义指向Node类型的指针变量,指向下一个节点
    Node();            //构造函数
    void init();    //初始化函数
    void print();    //打印节点坐标
};
Node::Node()
{
    x_=0;            //赋初值
    y_=0;
}
void Node::init()
{
    cout<<"x,y=";    //键盘输入节点坐标
    cin>>x_>>y_;
}
void Node::print()
{
    cout<<"结点坐标:"<<"("<<x_<<","<<y_<<")"<<endl;
}
/********************************************/
Node* CreateNodes(Node *head)//创建链表,从前向后
{
    Node *p1,*p2;
    int flag;
    p1=(class Node*)malloc(sizeof(class Node));
    p2=(class Node*)malloc(sizeof(class Node));
    p1->init();                //读入第一个点
    head=p1;                //把第一个点的地址给头指针head;
    flag=1;
    while(flag)
    {
        cout<<"还有结点吗?Y/N"<<endl;
        char s;
        cin>>s;
        switch(s)
        {
        case 'Y':
            //如果继续增加节点,则申请内存
            p2=(class Node*)malloc(sizeof(class Node));
            p2->init();        //读入新的节点信息
            p1->Node_=p2;    //将前面的点的指针指向新的节点
            p1=p2;            //将p1后移动一位
            break;
        case 'N':
            p1->Node_=NULL;    //使p1的指针指向NULL;
            flag=0;            //标志位置0;
            break;
        default:
            cout<<"输入错误"<<endl;
        }        
    }
    return head;
}
void PrintNodes(Node *head)
{
    Node *temp;
    temp=head;
    while(temp!=NULL)
    {
        temp->print();
        temp=temp->Node_;    //顺序输出
    }
    cout<<endl;
}
void main()
{
    Node* CreateNodes(Node *head);    //声明函数
    void PrintNodes(Node *head);    //声明函数
    Node *head;                        //定义节点
    head=NULL;
    head=CreateNodes(head);            //创建链表
    PrintNodes(head);                //打印结果
}

输出:

posted @ 2014-12-10 23:35  mt.luo  阅读(147)  评论(0编辑  收藏  举报