菜鸟求助啊啊,尾插法建立连个链表后再连接为何不行啊,下面是代码,望大神指导!!
#include"stdio.h"
#include"stdlib.h"
typedef struct node{
char info;
struct node *next;
}ListNode;
ListNode *create(){
ListNode *head,*tail,*p;
char ch;
head=(ListNode *)malloc(sizeof(ListNode));
head->next=NULL;
tail=head;
while((ch=getchar())!='#'){
p=(ListNode *)malloc(sizeof(ListNode));
p->info=ch;
tail->next=p;
tail=p;
}
tail->next=NULL;
return head;
}
ListNode *LINK(ListNode *head1,ListNode *head2){
ListNode *pre,*p;
pre=head1;
p=pre->next;
while(p){
pre=p;
p=p->next;
}
pre->next=head2->next;
return head1;
}
void print(ListNode *head){
ListNode *p;
p=head->next;
while(p){
putchar(p->info);
p=p->next;
}
}
void main(){
ListNode *head1,*head2,*head;
head1=create();
head2=create();
printf("before linking:\n");
print(head1);
print(head2);
printf("\nafter linking:\n");
head=LINK(head1,head2);
print(head);
printf("\n");
}
[解决办法]
这个没有问题。
你所遇到的问题可能是在建立链表时,多创建了一个内容为'\n'的节点。
第一个链表的内容输入完毕后,输入缓冲区内容1234567890#\n,当getchar到#时,调出循环,留\n在缓冲区里。第二个链表建立时,就首先读取了这个\n作为一个节点。这样在输出时,显示的情况就是链表1和链表2之间有换行,并不在一行显示。
在创建链表的循环完毕时,加上getchar();
[解决办法]
2个链表连接看起来没啥大问题,create函数最后加一句fflush(stdin)清空缓冲,不然第二链表第一个节点值是个回车,print函数后加一句putchar('\n')区隔一下。LINK函数return前head2->next=NULL吧,不然要是你在连接后释放第二条链表,就把附加到第一条链表的节点又释放掉...