单链表问题!!!请大家帮忙看一下~
#include <stdio.h>
#include <malloc.h>
typedef char ElemType;
typedef struct LNode /*定义单链表结点类型*/
{
ElemType data;
struct LNode* next;
}LNode,*LinkList;
void CreateList_L(LinkList &L,int n) /*创建单链表*/
{
//L=(LinkList)malloc(sizeof(LinkList*)); /*创建头结点*/
L=(LinkList)malloc(sizeof(LNode));
L-> next=NULL;
int i;
printf( "输入%d个元素: ",n);
for(i=n;i> 0;i--)
{
LinkList p;
//p=(LinkList)malloc(sizeof(LinkList*)); /*生成新结点*/
p=(LinkList)malloc(sizeof(LNode));
scanf( "%c ",&(p-> data));
p-> next=L-> next;
L-> next=p;
}
}
void DispList(LinkList L) /*输出链表元素*/
{
LinkList p=L-> next;
while(p!=NULL)
{
printf( "%c ",p-> data);
p=p-> next;
}
printf( "\n ");
}
int ListLength(LinkList L) /*输出链表长度*/
{
LinkList p=L;
int i=0;
while(p-> next !=NULL)
{
i++;
p=p-> next;
}
printf( "%d\n ",i);
return(i);
}
LinkList Reverse(LinkList &L)
{
LinkList p,q,r;
p=L;
if(L==0)
return 0;
q=p-> next;
L-> next=0;
while(q)
{
r=q-> next;
q-> next=p;
p=q;
q=r;
}
return p;
}
void main()
{
LinkList h;
int n;
printf( "初始化单链表,请输入链表长度: ");
scanf( "%d ",&n);
CreateList_L(h,n);
printf( "输出单链表: ");
DispList(h);
printf( "原地倒置输出单链表: ");
Reverse(h);
DispList(h);
printf( "链表长度为: ");
ListLength(h);
printf( "数据结构 ");
}
问题: 1, 输入元素(data的值)时,输入完一个后不能回车否则输入结束(然而如果用cin> > ...和cout < <...却可以输入完一个元素回车后,然后可以继续输入下一个元素).
2, 输出(DispList())时,和输入的元素一致.
PS: 希望有条件的朋友帮我上机调试执行一下就会发现毛病了,在此表示感谢!
[解决办法]
做了如下修改,请自己对照:
void CreateList_L(LinkList &L,int n) /*创建单链表*/
{
//L=(LinkList)malloc(sizeof(LinkList*)); /*创建头结点*/
L=(LinkList)malloc(sizeof(LNode));
L-> next=NULL;
int i;
printf( "输入%d个元素: ",n);
for(i=n;i> 0;i--)
{
LinkList p;
//p=(LinkList)malloc(sizeof(LinkList*)); /*生成新结点*/
p=(LinkList)malloc(sizeof(LNode));
fflush(stdin); //清空缓存区
scanf( "%c ",&(p-> data));
p-> next=L-> next;
L-> next=p;
}
//这个函数做了如下修改
void Reverse(LinkList L)
{
LinkList p,q,r;
p=L;
if(L==0)
return ;
q=p-> next;
p=0;
//L-> next=0;
while(q)
{
r=q-> next;
q-> next=p;
p=q;
q=r;
}
L-> next = p;
}
}