数据结构单链表逆置,存入数据后输出乱码或是运行不了,为什么?
问题描述:
目的:编写程序实现:
1、在原有的单链表中,将单链表实现逆置。 (即不增加新的结点)
2、程序要求单链表的内容由用户输入,并分别显示出逆置前和逆置后的单链表。
问题:存入数据,打印出逆置链表后,在vs里停止运行,在Dev-c++中无限循环乱码。
请问是什么问题,谢谢。
代码如下(c语言)
#include<stdio.h>
#include<stdlib.h>
struct LinkNode
{
int data;
struct LinkNode* next;
}LinkNode;
struct LinkNode* Inserve(struct LinkNode* head) //逆置,头插法
{
struct LinkNode* q, * p =NULL;
p = head ->next;
head -> next = NULL;
while (p != NULL)
{
q = p;
p = p->next;
q->next = head->next;
head->next = q;
}
return head;
}
void OutPut(struct LinkNode *head)
{
struct LinkNode* p;
p = head->next;
while (p )
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
struct LinkNode* Init() //初始化
{
int i = 0,a=0;
char choose = '\0';
struct LinkNode* p = NULL;
struct LinkNode* head = (struct LinkNode*)malloc(sizeof(struct LinkNode));
p = head;
while (1)
{
printf("请输入第%d个链表数据:", i);
scanf_s("%d", &a);
p->data = a;
struct LinkNode* q = NULL;
q = (struct LinkNode*)malloc(sizeof(struct LinkNode));
q->data = a;
q->next = p->next;
p->next = q;
p = q;
printf("是否还要继续输入(Y/N):");
scanf_s(" %c", &choose);
if (choose == 'N')
{
break;
}
i++;
}
return head;
}
int main()
{
struct LinkNode* L;
L = Init();
printf("链表转置前的数据:\n");
OutPut(L);
L = Inserve(L);
printf("链表转置后的数据:\n");
OutPut(L);
return 0;
}