线性表的实现形式,单链表形式。单链表的操作很多,有创建,输出,插入,删除,查找,求表长,释放空间,等。下面的仅仅是我写的,创建和输出单链表,带有头结点。
下面是我编写的创建单链表和输出单链表,还是一如既往的错误多多。待修改:
#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。经过改动,最终成功了。
本文详细介绍了如何使用C语言实现单链表的创建和输出功能,包括输入节点值直至输入特定结束值来终止链表创建的过程。通过实例演示了在链表中插入和链接节点的方法,并展示了如何正确地在输出时遍历并显示链表内容。
2691

被折叠的 条评论
为什么被折叠?



