assign1.c文件
#include "assign1.h"
//创建头结点
l_p create_link()
{
l_p H = (l_p)malloc(sizeof(link));
if(H==NULL)
{
printf("空间申请失败\n");
return NULL;
}
H->len = 0;
H->next = NULL;
return H;
}
//创建结点
l_p create_node(datatype data)
{
l_p new = (l_p)malloc(sizeof(link));
if(new==NULL)
{
printf("空间申请失败\n");
return NULL;
}
new->data = data;
return new;
}
//判空
int empty_link(l_p H)
{
if(H==NULL)
{
printf("入参为空");
return -1;
}
return H->next==NULL?1:0;
}
//头插
void insert_head(l_p H, datatype data)
{
if(H==NULL)
{
printf("入参为空");
return;
}
l_p new = create_node(data);
new->next = H->next;
H->next = new;
H->len++;
}
//尾部输出
int output_tail(l_p H)
{
if(H==NULL)
{
printf("入参为空");
return -1;
}
if(empty_link(H))
{
printf("链表为空\n");
return -2;
}
l_p p = H;
while(p->next->next!=NULL)
{
p = p->next;
}
l_p del = p->next;
int i = del->data;
p->next = NULL;
free(del);
H->len--;
return i;
}
//打印
void out_put(l_p H)
{
if(H==NULL)
{
printf("入参为空");
return;
}
l_p p = H->next;
while(p!=NULL)
{
printf("%d->",p->data);
p = p->next;
}
}
assign1.h文件
#ifndef __ASSIGN1_H__
#define __ASSIGN1_H__
#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct link
{
union
{
datatype data;
int len;
};
struct link *next;
}link,*l_p;
//创建头结点
l_p create_link();
//创建结点
l_p create_node(datatype data);
//判空
int empty_link(l_p H);
//头插
void insert_head(l_p H, datatype data);
//尾部输出
int output_tail(l_p H);
//打印
void out_put(l_p H);
#endif
main.c文件
#include "assign1.h"
int main(int argc, char *argv[])
{
/*FILE* wfp = fopen(argv[1],"w");
if(wfp==NULL)
{
return -1;
}*/
FILE* rfp = fopen(argv[1],"r");
if(rfp==NULL)
{
return -1;
}
l_p H = create_link();
//在链表中放入数据
insert_head(H,1);
insert_head(H,2);
insert_head(H,3);
insert_head(H,4);
insert_head(H,5);
output_tail(H);
out_put(H);
printf("\n");
//将链表数据放入到指定文件中
/*while(1)
{
int i;
i = output_tail(H);
if(i==-2)
{
break;
}
fprintf(wfp,"%d\n",i);
}
out_put(H);
printf("\n");*/
//将文件中的数据放入到链表中
while(1)
{
int j;
int res = fscanf(rfp,"%d",j);
fscanf(rfp,"%d",j);
if(res!=1)
{
break;
}
insert_head(H,j);
}
out_put(H);
printf("\n");
//fclose(wfp);
fclose(rfp);
return 0;
}