假设没有头结点,但是有头指针/* 链表结构 */
typedef struct Node
{
char data;
struct Node *prior;
struct Node *next;
} node, *linklist;
linklist CreateList(void) // 返回的是结构指针类型
{
int i = 3; // 申请3个结点
linklist head = NULL, target, temp;
while(i--)
{
/* 申请一个内存空间 */
temp = (linklist)malloc(sizeof(node));
if ( !temp ) //判断是否申请失败
exit(-1);
if (head == NULL) // 判断头指针有没有指向(链表是不是空)
head = temp; // 若空就头指针指向该结点
else
{ // 前结点后指针指向新申请结点,申请的结点前指针指向前一个结点
target->next = temp;
temp->prior = target;
}
target = temp; //前结点移动到申请的这个结点用于下一次添加
}
/* 最后一个结点后指针指向头结点,头结点前指针指向最后结点 */
target->next = head;
head->prior = target;
return head; //返回头结点就是整个链表
}
|