20140502 static_cast和dynamic_cast的类型检查 双链表建立,删除,打印

本文详细介绍了C++中static_cast和dynamic_cast的使用及区别,并提供了双链表的创建、删除和打印等实用代码示例。

1、static_cast和dynamic_cast的类型检查

  • static_cast的类型检查:只检查无关类之间的转换

CBaseY* pY1 = static_cast<CBaseY*>(pX);   // 错误,编译未通过, 类型指向是无关的 (解释:指针变量PX是CBaseX类,现在要将其转换为CBaseY类(和CBasex毫无关系))

  • dynamic_cast的类型检查是全面的(父类是否有虚函数),包括无关类的检查,失败返回0。

CBaseY* pY1 = dynamic_cast<CBaseY*>(pX);  // pY最终等于0(编译通过,但是转换未成功),前提是pX必须包含虚函数

2、双链表建立,删除,打印

#include<iostream>
#include<stdio.h>
#include <string>
#include<conio.h>

typedef struct student
{
    int data;
    struct student *next;
    struct student *pre;
}dnode;

dnode *create() //尾插法建立带头结点的双链表
{
    dnode *head,*p,*s;
    int x=0;
    head=(dnode *)malloc(sizeof(dnode));
    head->data=0;
    head->pre=NULL;
    head->next=NULL;
    p=head;
    printf("please input data (end by 0):");
    scanf("%d",&x);
    while(x!=0)
    {
        s=(dnode *)malloc(sizeof(dnode));
        s->data=x;
        s->pre=p;
        s->next=p->next;
        p->next=s;
        p=s;
        printf("please input data (end by 0):");
        scanf("%d",&x);
    }
    return head;
};

void delnode(dnode *head,int num)
{
    dnode *p=head->next;
    while(p!=NULL)
    {
        if(num==p->data)
        {
            p->pre->next=p->next;
            if(p->next!=NULL)    //最后一个节点
                p->next->pre=p->pre;
            free(p);
            break;
        }
        p=p->next;
    }
    printf("could not find the node\n");
}


void display1(dnode *head)  //正向打印
{
    dnode *p=head->next;
    while(p!=NULL)
    {
        printf("%d  ",p->data);
        p=p->next;
    }
    printf("\n");
}
void display2(dnode *head)//反向打印
{
    dnode *p=head;
    while(p->next!=NULL)
    {
        p=p->next;
    }
    while(p->pre!=NULL)
    {
        printf("%d  ",p->data);
        p=p->pre;
    }
    printf("\n");
}



void main()
{
    dnode *head=create();
    delnode(head,4);
    display1(head);
    display2(head);
}

转载于:https://www.cnblogs.com/yexuannan/p/3704409.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值