怎么求线性表的长度,我需要一个线性表的定义,赋值,然后求线性表的长度。

这是我的数据结构作业,我明天要交作业了。求求高手们。

#include<stdio.h>
#include<stdlib.h>
/*线性表*/
struct TLink {
int data;
struct TLink * next;
};/*end struct TLink*/

/*生成新元素*/
struct TLink * new_item(int number)
{
struct TLink * r = 0;
r = (struct TLink *)malloc(sizeof(struct TLink));
r->data = number;
r->next = 0;
return r;
}/*end new_item*/

/*在线性表中查询数据*/
struct TLink * lookup(struct TLink * root, int number)
{
struct TLink * h = root;
while(h) {
if (h->data == number) return h;
h = h->next ;
}/*end lookup*/
return 0;
}

/*在线性表中追加一个数据*/
void append(struct TLink * * root, int number)
{
struct TLink * r = 0, * n = 0;
if (!root) return ;

/*不记录重复元素*/
if (lookup(*root, number)) return;

/*如果表为空则新建表*/
r = *root;
if (!r) {
*root = new_item(number);
return ;
}/*end if*/

/*为保证为有序线性表,如果数据比表头还小则作为表头*/
if (number < r->data ) {
n = new_item(number);
n->next = r;
*root = n;
return ;
}/*end if*/

/*在有序线性表中查找位置插入元素*/
while(r) {
n = r->next ;

/*如果已经是表尾则直接追加*/
if (!n) {
n = new_item(number);
r->next = n;
return ;
}/*end if*/

/*在中央某处插入*/
if (number < n->data ) {
r->next = new_item(number);
r->next->next = n;
return ;
}/*end if*/
r = n;
}/*end while*/
}/*end append*/

/*打印有序线性表*/
void print(struct TLink * root)
{
int total = 0;
struct TLink * r = root;
printf("【");
while(r) {
printf("%d ", r->data );
r = r->next ;
total ++;
}/*end while*/
printf("\b】\n");
printf("线性表总长度 = %d\n", total);
}/*end print*/

int main(void)
{
int i = 0; struct TLink * x=0;
int a[] = {8,4,3,9,5,1};
printf("原数据为:\n数组【");
for(i = 0; i < 6; i++) {
printf("%d ", a[i]);
append(&x, a[i]);
}/*next*/
printf("\b】\n转换为有序线性表\n:");
print(x);
return 0;
}
温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答