C++中结构体和最简单链表

定义结构体时:

typedef struct _linklist
{
int x;
_linklist *next;
}linklist,*linklist;

其中_linklist相当于结构体的别名,这样每次在使用这个结构体定义变量时就不用都加struct linklist lt;

而只用 _linklist lt ; 即可。C++中可以不加typedef

C++中使用:

struct _linklist{
   int x, y;
};
就可以定义一个名为_linklist的结构体,C语言并不支持在struct后使用标识符定义结构体的名字,_linklist将会被忽略,这相当于定义了一个没有名字的结构体。所以,在C语言中,一般使用typedef来定义结构体,上面的例子可以改为:

typedef struct _linklist{
   int x, y;
}linklist;

_linklist要不要都可以。

typedef和define的区别

1. Unlike #define, typedef is limited to giving symbolic names to types only and not to values.

2. The typedef interpretation is performed by the compiler, not the preprocessor.

3. Within its limits, typedef is more flexible than #define.

typedef的两类陷阱:

陷阱一: 
记住,typedef是定义了一种类型的新别名,不同于宏,它不是简单的字符串替换。比如: 
先定义: 
typedef   char*   PSTR; 
然后: 
int   mystrcmp(const   PSTR,   const   PSTR); 

const   PSTR实际上相当于const   char*吗?不是的,它实际上相当于char*   const。 
原因在于const给予了整个指针本身以常量性,也就是形成了常量指针char*   const。 
简单来说,记住当const和typedef一起出现时,typedef不会是简单的字符串替换就行。 

陷阱二: 
typedef在语法上是一个存储类的关键字(如auto、extern、mutable、static、register等一样),虽然它并不真正影响对象的存储特性,如: 
typedef   static   int   INT2;   //不可行 
编译将失败,会提示“指定了一个以上的存储类”。 

使用结构体指针时直接内存操作避免了栈空间开辟结构变量空间需求,节省内存。

linklist例子:

#include <iostream>

typedef struct _linklist{
int x;
_linklist *next;
}linklist;

void createlist();
void createlist()
{
linklist *root; /* this wont change, or we would lose the list in the memory */
linklist *conductor; /* this will point to each node as it traverses the lis */

root = new linklist; /* set it to actually point to something */
root->next = 0;
root->x = 25;
conductor = root; /* The conductor points to the first node */
if (conductor!=0){
   while (conductor->next!=0){ /* make sure there is a place to start */
    cout << conductor->x << endl;
    conductor = conductor->next;
   }
   cout << conductor->x << endl; /* output the last node */
}

conductor->next = new linklist; /* Creates a node at the end of the list */
conductor = conductor->next; /* Points to that node */
conductor->next=0; /* Prevents it from going any further */
conductor->x=4;

}

本文使用Blog_Backup未注册版本导出,请到soft.pt42.com注册。

转载于:https://www.cnblogs.com/aquar/archive/2009/11/08/3451518.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值