#include<iostream>
#include<cstdio>
#include<string>
#include<malloc.h>
using namespace std;
typedef struct mylist
{
void* head;
void* tail;
} List,*pList;
typedef struct mynode
{
void* next;
void* prev;
int data;
} Node,*pNode;
pList createlist()
{
pList root;
pNode temp;
int n;
root = (pList)malloc(sizeof(List));
root->head = NULL;
root->tail = NULL;
printf("input data number:");
scanf("%d",&n);
if(n&&NULL==root->head)
{
temp = (pNode)malloc(sizeof(Node));
printf("data1:");
scanf("%d",&temp->data);
temp->next = (pList)root;
temp->prev = (pList)root;
root->head = (pNode)temp;
root->tail = (pNode)temp;
n--;
}
for(int i=1; i<=n ; i++)
{
temp = (pNode)malloc(sizeof(Node));
printf("data%2d:",i);
scanf("%d",&temp->data);
temp->next = (pList)root;
temp->prev = (pNode)root->tail;
((pNode)(root->tail))->next = (pNode)temp;
root->tail = (pNode)temp;
}
return root;
}
void printlist(pList root)
{
pNode temp = (pNode)root->head;
int i = 1;
while(temp!=(pNode)root)
{
printf("data%2d:%d\n",i++,temp->data);
temp = (pNode)temp->next;
}
/*temp = (pNode)root->tail;
while(temp!=(pNode)root)
{
printf("data%2d:%d\n",--i,temp->data);
temp = (pNode)temp->prev;
}*/
}
int main()
{
pList root;
root = createlist();
printlist(root);
}
双向链表的面试题要求list和node是不同的结构体,所以这里使用的void指针
1声明LIst和Node结构体
2创建链表
3尾部追加
4头部删除
都很简单,我只写了创建 打印时测试用的,主要就是试试void类型的指针用法
上面的所有都加上了显示类型转换
以下去掉了不必要的类型转换
总结一下,
1.当给void类型指针赋值的时候不需要显示类型转换
2.void给void赋值不需要转换
3.当void给其他类型的指针赋值时需要显示类型转换
4.当void*与不同类型的指针比较的时候需要显示类型转换
5.当需要链式的时候需要显示类型转换。
注释标记对应1,2,3,4,5的情况
注意:不转换不等于不需要转换,而是编译器隐式转换了
#include<iostream>
#include<cstdio>
#include<string>
#include<malloc.h>
using namespace std;
typedef struct mylist
{
void* head;
void* tail;
} List,*pList;
typedef struct mynode
{
void* next;
void* prev;
int data;
} Node,*pNode;
pList createlist()
{
pList root;
pNode temp;
int n;
root = (pList)malloc(sizeof(List)); //malloc属于情况3
root->head = NULL;
root->tail = NULL;
printf("input data number:");
scanf("%d",&n);
if(n&&NULL==root->head)
{
temp = (pNode)malloc(sizeof(Node)); //3
printf("data1:");
scanf("%d",&temp->data);
temp->next = root; //1
temp->prev = root; //1
root->head = temp; //1
root->tail = temp; //1
n--;
}
for(int i=1; i<=n ; i++)
{
temp = (pNode)malloc(sizeof(Node)); //3
printf("data%2d:",i);
scanf("%d",&temp->data);
temp->next = root; //1
temp->prev = root->tail; //2
((pNode)(root->tail))->next = temp; //5
root->tail = temp; //1
}
return root;
}
void printlist(pList root)
{
pNode temp = (pNode)root->head; //3
int i = 1;
while(temp!=(pNode)root) //4
{
printf("data%2d:%d\n",i++,temp->data);
temp = (pNode)temp->next; //3
}
/*temp = (pNode)root->tail;
while(temp!=(pNode)root)
{
printf("data%2d:%d\n",--i,temp->data);
temp = (pNode)temp->prev;
}*/
}
int main()
{
pList root;
root = createlist();
printlist(root);
}