C语言随笔小算法:创建双向链表
双向链表两个指针域!head定住,tail移动!
代码:
#include "stdlib.h"
#include "stdio.h"
#include "malloc.h"
// 创建双向链表
typedef struct STUDENT
{
int age;
int score[3];
char *name;
int order;
} student, *_pstudent;
/*
**定义数据域
*/
typedef struct NODE
{
struct STUDENT element; //数据类容
struct NODE *pre; //注意,只能使用节点指针类型struct NODE*
struct NODE *next; //注意,只能使用节点指针类型struct NODE*
} node, *_pnode;
/******************************************************************************
* Function - Tracker_Get_IMEI_Req
*
* Purpose - 创建一个num个节点的双向链表
*
* Description -
*
* modification history
* ----------------------------------------
* v1.0 , 2011-11-02, ysheng written
* ----------------------------------------
******************************************************************************/
_pnode initCreate(int num);
/******************************************************************************
* Function - Tracker_Get_IMEI_Req
*
* Purpose - 主函数入口
*
* Description -
*
* modification history
* ----------------------------------------
* v1.0 , 2011-11-02, ysheng written
* ----------------------------------------
******************************************************************************/
/******************************************************************************
* Function - Tracker_Get_IMEI_Req
*
* Purpose - 创建一个num个节点的单项链表
*
* Description -
*
* modification history
* ----------------------------------------
* v1.0 , 2011-11-02, ysheng written
* ----------------------------------------
******************************************************************************/
_pnode initCreate(int num)
{
struct NODE *head = NULL; //头节点指针
struct NODE *normal_node = NULL; //普通节点指针
struct NODE *tail = NULL; //尾结点指针
int i = 1;
/*创建链表的思想就是head作为定点,tail作为动点*/
for(i = 1; i < num + 1; i++)
{
normal_node = (node *)malloc(sizeof(node));
if(head == NULL)
{
head = tail = normal_node;
}
normal_node->element.order = i;
printf("initCreate()-->>创建%d个节点!\n", i);
tail->next = normal_node; //将新创的节点的地址放到前一个节点的next变量里
normal_node->pre = tail; //新创建的节点的pre指针指向前一个节点
tail = normal_node; //移动tail指针至新创建的节点
}
tail->next = NULL; //最后一个节点的指针域存放head头指针的指针域,形成双向链表
printf("initCreate()-->>创建双向链表完成!\n");
return head;
}
// -->入队
/************************
7 |6 |5 |4 |3 |2 |1 | 0
************************/
// -->出队
void main(void)
{
_pnode head = initCreate(6);
printf("head地址=%p\n",head);
printf("head->next->pre地址=%p\n",head->next->pre);
}