帮忙看个C++程序吧 输出的是乱码
用后插法建立一个链表,并输出数据域,输出的是乱码,麻烦高手帮忙看下
#include<iostream>
#include<stdio.h>
using namespace std;
typedef struct lianbiao{
char data;
struct lianbiao *next;
}Linklist;
typedef Linklist *ListNode;
ListNode head;
ListNode creatlist() //建立链表
{
ListNode head = new Linklist[1];
ListNode first= head;
//head->next = NULL;
Linklist *q;
char ch;
while (getchar() !='\n')
{
q = new Linklist[1];
q->data = ch;
head->next = q;
head = head->next;
}
q->next = NULL;
return first;
}
int Length(ListNode head) //求链表的长度
{
int i=0;
ListNode q = head->next;
while(q!=NULL)
{
q = q->next;
i++;
}
cout<<i<<endl;
return 0;
}
void show(ListNode head)
{
while(head!=NULL)
{
head = head->next;
cout<<head->data;
}
}
int main()
{
ListNode first = creatlist();
show(first);
return 0;
}
[解决办法]
#include<iostream>
#include<stdio.h>
using namespace std;
typedef struct lianbiao{
char data;
struct lianbiao *next;
}Linklist;
typedef Linklist *ListNode;
//ListNode head;
ListNode creatlist() //建立链表
{
ListNode head = new Linklist;
memset(head, 0, sizeof(Linklist));
ListNode first= head;
//head->next = NULL;
Linklist *q;
char ch;
while (ch = getchar())
{
if(ch == '\n')
break;
q = new Linklist[1];
//memset(q 0, sizeof(ListNode));
q->data = ch;
head->next = q;
head = head->next;
}
head->next = NULL;
return first;
}
int Length(ListNode head) //求链表的长度
{
int i=0;
ListNode q = head->next;
while(q!=NULL)
{
q = q->next;
i++;
}
cout<<i<<endl;
return 0;
}
void show(ListNode head)
{
while(head->next!=NULL)
{
head = head->next;
cout<<head->data;
}
}
int main()
{
ListNode first = creatlist();
show(first);
return 0;
}
改好了
ch = getchar()你上面么给ch赋值