已结贴√
问题点数:20 回复次数:8
大神进~关于结构体数据的强制类型转换~已经晕头转向~
#include
#include
#include "LinkList.h"
typedef void LinkList;
typedef struct _tag_LinkListNode LinkListNode;
typedef struct _tag_LinkList
{
LinkListNode header; //线性表首地址也即表头
int length; //线性表长度也即表长
} TLinkList;
LinkList* LinkList_Create() // O(1)
{
TLinkList* ret = (TLinkList*)malloc(sizeof(TLinkList));
if( ret != NULL )
{
ret->length = 0; //当前数组长度置0
ret->header.next = NULL; //头指针的next为空
}
return ret;
}
void LinkList_Destroy(LinkList* list) // O(1)
{
free(list);
}
void LinkList_Clear(LinkList* list) // O(1)
{
TLinkList* sList = (TLinkList*)list;
if( sList != NULL )
{
sList->length = 0;
sList->header.next = NULL;
}
}
int LinkList_Length(LinkList* list) // O(1)
{
TLinkList* sList = (TLinkList*)list;
int ret = -1;
if( sList != NULL )
{
ret = sList->length;
}
return ret;
}
int LinkList_Insert(LinkList* list, LinkListNode* node, int pos) // O(n)
{
TLinkList* sList = (TLinkList*)list;
int ret = (sList != NULL) && (pos >= 0) && (node != NULL);
int i = 0;
if( ret )
{
LinkListNode* current = (LinkListNode*)sList; // 问题一 :此处强制类型转换将TLinkList*强制转换为LinkListNode*
for(i=0; (inext != NULL); i++)
{
current = current->next;
}
node->next = current->next;
current->next = node;
sList->length++;
}
return ret;
}
LinkListNode* LinkList_Get(LinkList* list, int pos) // O(n)
{
TLinkList* sList = (TLinkList*)list;
LinkListNode* ret = NULL;
int i = 0;
if( (sList != NULL) && (0 <= pos) && (pos < sList->length) )
{
LinkListNode* current = (LinkListNode*)sList;
for(i=0; i
{
current = current->next;
}
ret = current->next;
}
return ret;
}
LinkListNode* LinkList_Delete(LinkList* list, int pos) // O(n)
{
TLinkList* sList = (TLinkList*)list;
LinkListNode* ret = NULL;
int i = 0;
if( (sList != NULL) && (0 <= pos) && (pos < sList->length) )
{
LinkListNode* current = (LinkListNode*)sList;
for(i=0; i
{
current = current->next;
}
ret = current->next;
current->next = ret->next;
sList->length--;
}
return ret;
}
struct Value
{
LinkListNode header;
int v;
};
// ———————————————————以此往下为主函数部分——————————————————————
int main(int argc, char *argv[])
{
int i = 0;
LinkList* list = LinkList_Create();
struct Value v1;
struct Value v2;
struct Value v3;
struct Value v4;
struct Value v5;
v1.v = 1;
v2.v = 2;
v3.v = 3;
v4.v = 4;
v5.v = 5;
LinkList_Insert(list, (LinkListNode*)&v1, LinkList_Length(list)); //问题二:强制类型转换,将&v1又转换为LinkListNode*类型
LinkList_Insert(list, (LinkListNode*)&v2, LinkList_Length(list));
LinkList_Insert(list, (LinkListNode*)&v3, LinkList_Length(list));
LinkList_Insert(list, (LinkListNode*)&v4, LinkList_Length(list));
LinkList_Insert(list, (LinkListNode*)&v5, LinkList_Length(list));
for(i=0; i
{
struct Value* pv = (struct Value*)LinkList_Get(list, i);
printf("%d\n", pv->v);
}
while( LinkList_Length(list) > 0 )
{
struct Value* pv = (struct Value*)LinkList_Delete(list, 0);
printf("%d\n", pv->v);
}
LinkList_Destroy(list);
return 0;
}
//这是基本的动态链表操作,只不过表中用了很多的强制类型转换。。。楼主不明白的是为什么所定义的结构体根本不同,却可以通过强制转换实现这些操作?
//还有就是什么时候可以强制转换什么时候不可以~