#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是不同的結(jié)構(gòu)體抬驴,所以這里使用的void指針
1聲明LIst和Node結(jié)構(gòu)體
2創(chuàng)建鏈表
3尾部追加
4頭部刪除
都很簡單领曼,我只寫了創(chuàng)建 打印時測試用的,主要就是試試void類型的指針用法
上面的所有都加上了顯示類型轉(zhuǎn)換
以下去掉了不必要的類型轉(zhuǎn)換
總結(jié)一下搀玖,
1.當給void類型指針賦值的時候不需要顯示類型轉(zhuǎn)換
2.void給void賦值不需要轉(zhuǎn)換
3.當void給其他類型的指針賦值時需要顯示類型轉(zhuǎn)換
4.當void*與不同類型的指針比較的時候需要顯示類型轉(zhuǎn)換
5.當需要鏈式的時候需要顯示類型轉(zhuǎn)換余境。
注釋標記對應(yīng)1,2灌诅,3芳来,4,5的情況
注意:不轉(zhuǎn)換不等于不需要轉(zhuǎn)換猜拾,而是編譯器隱式轉(zhuǎn)換了
#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);
}