输出链表结点[原创]
所有数据结构的代码都是大一那会一个人在机房敲的,虽说现在天天面向对象,不过我觉得受益还是很大的。
1
#include <stdio.h>2
#include <malloc.h>3

struct node
{/**//*定义一个结点的结构体,包含一个数据域及一个指针域*/4
char data;5
struct node * next;6
};7

8

struct link
{/**//*定义一个链的结构体,包含一个指向结点类型的指针*/9
struct node * head;10
int i;11
};12

13

/**//*==================================*/14

void print_1(struct link a)
{15
struct node * q;16
q=a.head;17

if(q->next==NULL)
{/**//*判断是否为空表用q->next*/18
printf("\nthe list is NULL\n");19
return;20
}21
printf("\nprint_1,the list=== ");22

while(q!=NULL)
{/**//*为了能够输出所有元素,用q*/23
printf("%c_ ",q->data);24
q=q->next;25
}26
}27

28

29

void print_2(struct link * a)
{30
struct node * q;31
q=a->head;32

if(q->next==NULL)
{/**//*判断是否为空表用q->next*/33
printf("\nthe link is null\n");34
return;35
}36

37
printf("\nprint_2,the list=== ");38

while(q!=NULL)
{/**//*为了能够输出所有元素,用q*/39
printf("%c_ ",q->data);40
q=q->next;41
}42
}43

/**//*======================================*/44

int init(struct link *p)
{ /**//*初始化链表的函数*/45
printf("\ninit():\n");46

47
p->head=(struct node *)malloc(sizeof(struct node));48
p->head->data='L';49
printf("p->head->data=%c\n",p->head->data);50
p->head->next=NULL;51
}52

53

54

int add(struct link *p,char tem)
{/**//*向链表中添加结点的函数*/55
struct node * q;56
q=p->head;57

58

if(q->next==NULL)
{/**//*考虑到一开始表中元素为空的情况----很重要*/59
q->next=(struct node *)malloc(sizeof(struct node));60
q=q->next;61
q->data=tem;62
q->next=NULL;63

return;/**//*此处return不能少,否则链表的头两个元素会始终一样*/64
}65

66
while(q->next!=NULL) q=q->next;67

68
q->next=(struct node *)malloc(sizeof(struct node));69
q=q->next;70
q->data=tem;71
q->next=NULL;72

73
}74

/**//*==============================================*/75

main()
{76
int i;77
char tem='a';78
struct node x,*lx;79
struct link y,*ly;80
y.head=&x; ly=&y;81

82
init(ly);83

84
print_1(y);85
print_2(ly);86

87

for(i=1;i<=10;i++)
{88
add(ly,tem++);89
}90

91
print_1(y);92
print_2(ly);93

94
getch();95

96
}97

98

99

100

101

102

103

104

105

106


浙公网安备 33010602011771号