|
10鱼币
当输入的数据错误时scanf返回值为零,正常会不执行循环继续往下执行程序的,但不知道怎么回事会返回段错误。
求解。。。
#include <stdio.h>
#include <stdlib.h>
#define ElemType int
typedef struct Lnode
{
ElemType data;
struct Lnode *prior, *next;
}Lnode, *LinkList;
void insert(LinkList L);
void change(LinkList L, int i);
void print(LinkList L);
void insert(LinkList L)
{
ElemType n;
Lnode *p;
_Bool flag = 1;
p = L;
printf("请输入链表数据:\n");
while (flag)
{
flag = scanf("%d", &n);
if (flag)
{
Lnode *new;
new = (Lnode*)malloc(sizeof(Lnode));
if (new == NULL)
{
printf("内存分配失败!\n");
exit(1);
}
new->data = n;
p->next = new;
new->next = NULL;
new->prior = p;
p = new;
}
}
}
void change(LinkList L, int i)
{
Lnode *p, *pre;
p = L->next;
while (i-- && p != NULL)
{
p = p->next;
}
pre = p->prior;
p->prior = pre->prior;
pre->prior->next = p;
pre->next = p->next;
p->next->prior = pre;
p->next = pre;
pre->prior = p;
}
void print(LinkList L)
{
Lnode *p;
p = L->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
putchar('\n');
}
int main(void)
{
int p;
LinkList L;
L = (LinkList)malloc(sizeof(Lnode));
if (L == NULL)
{
printf("内存分配失败!\n");
exit(1);
}
L->prior = NULL;
L->next = NULL;
insert(L);
printf("请输入指针位置:");
scanf("%d", &p);
change(L, p);
printf("交换之后的链表:");
print(L);
return 0;
}
|
|