关于链表插入的操作 大家帮看看 是否存在什么bug一类的
程序代码:// tlink.cpp : 定义控制台应用程序的入口点。
//
#include <stdio.h>
#include <malloc.h>
typedef struct date
{
unsigned int month;
unsigned int day;
unsigned int year;
struct date* next;
}tdate,*pdate;
//链表插入函数
//为了方便操作 把head指针传入 实际上没有参与计算
//inspos 为中间插入时的索引 其他插入方式无效
//beginp 为插入数据块的首地址
//flag为插入标志 0 尾部插入 1 头部插入 2 中间插入
//endp就是所谓的后驱指针 我理解为临时变量
pdate linkins(pdate head,pdate beginp,pdate endp,unsigned int flag,unsigned inspos)
{
pdate tmp=NULL;
if(flag==0)
{
beginp->next=NULL;
endp->next=beginp;
endp=beginp;
}
if(flag==1)
{
endp=head;
tmp=head->next;
endp->next=beginp;
endp=beginp;
beginp->next=tmp;
}
if(flag==2)
{
pdate tp;
tp=head->next;
int n=1;
while(tp!=NULL)
{
tp=tp->next;
n++;
if(n==inspos)
{
endp=tp;
tmp=tp->next;
break;
}
}
endp->next=beginp;
endp=beginp;
beginp->next=tmp;
}
return head;
}
int main(int argc, char* argv[])
{
pdate head;
pdate beginp;
pdate endp;
pdate tmp;
//链表正常创建
beginp=(pdate)malloc(sizeof(tdate));
head=beginp;
endp=beginp;
int i;
for(i=0;i<3;i++)
{
beginp=(pdate)malloc(sizeof(tdate));
scanf("%u%u%u",&beginp->month,&beginp->day,&beginp->year);
beginp->next=NULL;
endp->next=beginp;
endp=beginp;
}
printf("////////////正常输出示例//////////////////\n");
beginp=head->next;
while(beginp!=NULL)
{
printf("%6u%4u%4u\n",beginp->year,beginp->month,beginp->day);
beginp=beginp->next;
}
//在链表尾部插入示例:
beginp=(pdate)malloc(sizeof(tdate));
scanf("%u%u%u",&beginp->month,&beginp->day,&beginp->year);
head=linkins(head,beginp,endp,0,0);
printf("////////////在尾部插入后输出示例//////////////////\n");
beginp=head->next;
while(beginp!=NULL)
{
printf("%6u%4u%4u\n",beginp->year,beginp->month,beginp->day);
beginp=beginp->next;
}
//在链表头部插入示例:
beginp=(pdate)malloc(sizeof(tdate));
scanf("%u%u%u",&beginp->month,&beginp->day,&beginp->year);
head=linkins(head,beginp,endp,1,0);
printf("////////////在头部插入后输出示例//////////////////\n");
beginp=head->next;
while(beginp!=NULL)
{
printf("%6u%4u%4u\n",beginp->year,beginp->month,beginp->day);
beginp=beginp->next;
}
//在链表中间插入示例:
beginp=(pdate)malloc(sizeof(tdate));
scanf("%u%u%u",&beginp->month,&beginp->day,&beginp->year);
head=linkins(head,beginp,endp,2,2);
printf("////////////在链表中间插入后输出示例//////////////////\n");
beginp=head->next;
while(beginp!=NULL)
{
printf("%6u%4u%4u\n",beginp->year,beginp->month,beginp->day);
beginp=beginp->next;
}
///////////////////////////////////////////////////
free(head);
return 0;
}
/* 示例效果
1 1 1
2 2 2
3 3 3
////////////正常输出示例//////////////////
1 1 1
2 2 2
3 3 3
4 4 4
////////////在尾部插入后输出示例//////////////////
1 1 1
2 2 2
3 3 3
4 4 4
0 0 0
////////////在头部插入后输出示例//////////////////
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
9 9 9
////////////在链表中间插入后输出示例//////////////
0 0 0
1 1 1
9 9 9
2 2 2
3 3 3
4 4 4
*/









