链式物理结构3

来源:互联网 发布:java选择题题库 编辑:程序博客网 时间:2024/05/16 10:15
/*
   链式存储结构练习
   */
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int num;
struct node *p_next;
} node;
static node head, tail;
int main() {
node *p_node = NULL, *p_tmp = NULL;
    head.p_next = &tail;
//把一个新节点加入到链的末尾
for (p_node = &head;p_node != &tail;p_node = p_node->p_next) {
node *p_first = p_node;
node *p_mid = p_first->p_next;
node *p_last = p_mid->p_next;
if (p_mid == &tail) {
            p_tmp = (node *)malloc(sizeof(node));
if (p_tmp) {
p_tmp->num = 10;
p_tmp->p_next = NULL;
p_first->p_next = p_tmp;
p_tmp->p_next = p_mid;
}
break;
}
}
//把一个新节点加入到链的开头
    p_tmp = (node *)malloc(sizeof(node));
if (p_tmp) {
p_tmp->num = 5;
p_tmp->p_next = NULL;
p_tmp->p_next = head.p_next;
head.p_next = p_tmp;
}
//打印链中所有数据
    for (p_node = &head;p_node != &tail;p_node = p_node->p_next) {
node *p_first = p_node;
node *p_mid = p_first->p_next;
node *p_last = p_mid->p_next;
if (p_mid != &tail) {
printf("%d ", p_mid->num);
}
}
printf("\n");
//释放所有动态分配节点
while (head.p_next != &tail) {
        node *p_first = &head;
node *p_mid = p_first->p_next;
node *p_last = p_mid->p_next;
p_first->p_next = p_last;
free(p_mid);
p_mid = NULL;
}
return 0;
}













0 0