单链表就地逆置只逆置了前一半,怎么回事?
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct Node
{
char data;
struct Node *next;
}SLNode;
void ListInitiate(SLNode **head)
{
if((*head=(SLNode*)malloc(sizeof(SLNode)))==NULL)exit(1);
(*head)-> next=NULL;
}
int ListInsert(SLNode *head,char x)
{
SLNode *p,*q;
p=head;
while(p-> next!=NULL)
p=p-> next;
if(p-> next!=NULL)
{
printf( "error! ");
return 0;
}
if((q=(SLNode*)malloc(sizeof(SLNode)))==NULL)exit(1);
q-> data=x;
q-> next=NULL;
p-> next=q;
return 1;
}
int ListDelete(SLNode *head,char *x)
{
SLNode *p,*s;
p=head;
while(p-> next!=NULL && p-> next-> next!=NULL)
p=p-> next;
if(p-> next==NULL || p-> next-> next!=NULL)
{
printf( "error! ");
return 0;
}
s=p-> next;
*x=s-> data;
p-> next=NULL;
free(s);
return 1;
}
void Destroy(SLNode **head)
{
SLNode *p,*p1;
p=*head;
while(p!=NULL)
{
p1=p;
p=p-> next;
free(p1);
}
*head=NULL;
}
void main(void)
{
SLNode *head,*reset;
int i;
char x1,x2;
ListInitiate(&head);
ListInitiate(&reset);
printf( "hello,Zhu Dan,please enter 6 characters to the list:\n ");
for(i=0;i <11;i++)
{
scanf( "%c ",&x1);
if(ListInsert(head,x1)==0)
{
printf( "error\n ");
return;
}
}
for(i=0;i <11;i++)
{
if(ListDelete(head,&x2)==0)
{
printf( "error!\n ");
return;
}
else
{
if(ListInsert(reset,x2)==0)
{
printf( "error!\n ");
return;
}
else printf( "%c ",x2);
}
}
getch();
Destroy(&head);
Destroy(&reset);
}
在窗体输入q w e r t y u i o p a回车!
输出结果却是:y t r e w q.(注意printf( "%c ")没有空格).
如果把程序换成输入10个,则刚好只逆置前面5个.
如果程序不改(还是要求输入11个)的话,只输入10个,结果也是逆置前6个.
可是我就是找不到错误,帮帮我啊!
[解决办法]
typedef struct Node
{
char data;
struct Node *next;
Node(){ next = NULL;};
}SLNode;
[解决办法]
大的问题没有:
1)第一个节点没有数据
2)输入时11个字符不留空格,不回车:123456789ab,否则.空格和回车会加入到链表中.
[解决办法]
你单步调试一下,不就知道哪里有问题了嘛
[解决办法]
没有问题的 呵呵
楼主你输入的时候没发现你输入空格也算字符吗?
打印出来包含空格正好是11个
[解决办法]
同意楼上.
[解决办法]
空格属于输入链表的值
[解决办法]
上你当了,看了一下程序没问题,
运行后才发现是你输入的问题。
输入的空格也算一个字符哦
[解决办法]
晕,早知道我就先看一下大家发的帖再看程序了
楼主,你没事输什么空格啊!!!
[解决办法]
不过还是建议楼主
不要用exit(1),太暴力了
[解决办法]
解决了?