Turbo C写线性链表遇到奇怪问题
#include <stdio.h>#define NULL 0
struct unit
{
int num;
struct unit *next;
struct unit *forward;
};
struct unit *head;
struct unit *create(void)
{
struct unit *p1, *p2;
int i;
p2 = p1 = (struct unit*)malloc(sizeof(struct unit));
head = p1;
for (i = 0; i < 10; i++)
{
p1 -> num = i;
p2 = p1;
p1 = (struct unit*)malloc(sizeof(struct unit));
p2 -> next = p1;
p1 -> forward = p2;
}
p2 -> next = head;
head -> forward = p2;
}
void print()
{
struct unit *p;
int i = 0;
p = head;
printf("............\n");
for (i = 0; i < 10; i++)
{
printf("%d\n",p->num);
p = p -> next;
}
printf("\n");
p = head -> forward;
for (i = 0; i < 10; i++)
{
printf("%d\n",p->num);
p = p -> forward;
}
printf("............\n");
}
int search(int input)
{
struct unit *p;
if (head->num == input)
return 0;
else
{
p = head -> next;
do
{
if (p->num == input)
return 0;
else
p = p ->next;
}while(p != head);
}
return 1;
}
void delete()
{
struct unit *p;
int del;
p = head;
printf("Input the number you want to delete!\n");
scanf("%d\n",&del);
if (head->num == del)
head = p -> next;
if (search(del) == 1)
printf("The number you want to delete doesn't exist!\n");
else
{
while (p->next->num != del)
p = p -> next;
p -> next -> next -> forward = p;
p -> next = p -> next -> next;
}
print();
}
int searchcore()
{
int input;
printf("Please input the number you want to search!\n");
scanf("%d\n",&input);
return search(input);
}
void insert()
{
int ins,pos;
int i;
struct unit *p, *new;
printf("Please input the number you want to insert!\n");
scanf("%d\n",&ins);
printf("Please input the position you want to put the number!\n");
scanf("%d\n",&pos);
p = head;
for (i = 0; i < pos; i++)
p = p -> next;
new = (struct unit*)malloc(sizeof(struct unit));
new -> num = ins;
p -> next -> forward = new;
new -> next = p -> next;
p -> next = new;
new -> forward = p;
print();
}
main()
{
create();
/*print();
printf("\n");
if (searchcore() == 0)
printf("Found!\n");
else
printf("Not Found!\n");
delete(); */
insert();
getch();
}
小弟多年不写,前些天想写个Linear找找感觉
但是void insert()时遇到比较奇怪的事情
就是两次Scanf前一次被要求输入两次,好像第一次没有用,(这样就总共输入两次),但计算机采取的数据却只是3次中的两次,我以前从来没遇到过这种情况啊。。。
大家可以试试在自己这里运行,到底是我写的有问题,还是TC有问题呢?