线性表的实现形式,单链表形式。单链表的操作很多,有创建,输出,插入,删除,查找,求表长,释放空间,等。下面的仅仅是我写的,创建和输出单链表,带有头结点。
下面是我编写的创建单链表和输出单链表,还是一如既往的错误多多。待修改:
#include<iostream>
#include<malloc.h>
using namespace std;
typedef int elemtype;
typedef struct {
elemtype data;
struct nodetype *next;
} nodetype,*linklist;
struct nodetype* create(linklist& la);
void output(nodetype* h);
int main()
{
linklist head;
head=create(head);
output(head);
}
struct nodetype* create(linklist& la)
{
linklist la;
nodetype *r,*s;
int x;
cout <<"输入1000表示结束。" << endl;
cout << "输入结点值:" << endl;
cin >> x;
la=(linklist)malloc(sizeof(linknode));
la->next=NULL;
r=la;
while(x!=1000)
{
s=(linklist)malloc(sizeof(linknode));
s->data=x;
la->next=s;
r=s;
cout <<"输入结点值:" << endl;
cin >> x;
}
r->next=NULL;
return la;
}
void output(nodetype* h)
{
nodetype* q;
q=h->next;
if(q==NULL)
cout << "end" << endl;
else
cout << q->data << " ";
q=q->next;
}
#include<iostream>
# include "stdio.h"
# include "stdlib.h"
# include "malloc.h"
using namespace std;
typedef int elemtype;
typedef struct linknode {
elemtype data;
struct linknode *next;
} nodetype,*linklist;
nodetype* create(linklist& la);
void output(nodetype* h);
void main()
{
nodetype* head;
head=create(head);
output(head);
}
nodetype* create(linklist& la)
{
nodetype *r,*s;
int x;
cout <<"输入0表示结束。" << endl;
cout << "输入结点值:" << endl;
cin >> x;
la=(linklist)malloc(sizeof(linknode));
la->next=NULL;
r=la;
while(x!=0)
{
s=(linklist)malloc(sizeof(linknode));
s->data=x;
la->next=s;
r=s;
cout <<"输入结点值:" << endl;
cin >> x;
}
r->next=NULL;
return la;
}
void output(nodetype* h)
{
nodetype* q;
q=h->next;
if(q==NULL)
cout << "end" << endl;
else
cout << q->data << " ";
q=q->next;
}
经过观察,找到了错误,下面的运行成功。
#include<iostream>
# include "stdio.h"
# include "stdlib.h"
# include "malloc.h"
using namespace std;
typedef int elemtype;
typedef struct linknode {
elemtype data;
struct linknode *next;
} nodetype,*linklist;
nodetype* create(linklist& la);
void output(nodetype* h);
void main()
{
nodetype* head;
nodetype* ha;
ha=create(head);
output(ha);
}
nodetype* create(linklist& la)
{
nodetype *r,*s;
int x;
cout <<"输入0表示结束。" << endl;
cout << "输入结点值:" << endl;
cin >> x;
la=(linklist)malloc(sizeof(linknode));
la->next=NULL;
r=s=la;
while(x!=0)
{
s=(linklist)malloc(sizeof(linknode));
s->data=x;
r->next=s;
r=s;
cout <<"输入结点值:" << endl;
cin >> x;
}
r->next=NULL;
return la;
}
void output(nodetype* h)
{
nodetype* q;
q=h->next;
while(q!=NULL)
{
cout << q->data << " ";
q=q->next;
}
cout << "end" << endl;
}
主要错误有好多,首先结构体地方,定义时候有重复定义,并且创建函数返回类型错误。再者创建的时候,指针移动错误,应该是r移动,写成了la;还有就是在输出的时候用的if语句,if语句不具有循环作用,最后改为了while。经过改动,最终成功了。