把线性表的各种应用写了一下。比上次根伟完整了下。释放存储空间没有写。只是写了下思路。
#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(); //建立链表
void output(nodetype* h); //输出链表
int len(nodetype *h);//求链表长度
nodetype* find(nodetype* h,int i);//返回第i个位置的指针
nodetype* insert(nodetype* h,int i,int x);//在第i个位置插入x
nodetype* dele(nodetype*h,int i); //删除第i个数
void main()
{
int lenth;
nodetype*q;
nodetype* head;
head=create();
output(head);
lenth=len(head);
cout << lenth << endl;
cout << "查找第3个数的值。" << endl;
q=find(head,3);
cout << q->data << endl;
cout << "在第3个位置插入100" << endl;
insert(head,3,100);
output(head);
cout << "删除第4个数。" << endl;
dele(head,4);
output(head);
}
nodetype* create()
{
nodetype *r,*s,*la;
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;
}
int len(nodetype *h)
{
int i=0;
nodetype* p;
p=h;
while(p->next!=NULL) // 这个地方出错了,原来写的是p->next->data!=0.错误的,是指针为null,而非data。
{
p=p->next;
i++;
}
return i;
}
/* nodetype* find(nodetype* h,int i)// 此函数查找的是所找数的下一个
{
int j;
nodetype* p;
p=h;
for(j=0;j<=i;j++) //这个地方出错,应该是 j<i.
p=p->next;
return p;
}*/
nodetype* find(nodetype* h,int i)
{
int j;
nodetype* p;
p=h;
for(j=0;j<i;j++)
p=p->next;
return p;
}
nodetype* insert(nodetype* h,int i,elemtype x)//在单链表中第i个位置,插入x
{
nodetype* p,* s;
p=find(h,i-1);
s=(nodetype*)malloc(sizeof(nodetype)); //s=(*nodetype)malloc(sizeof(nodetype));错误
s->data=x;
s->next=p->next; // s=p->next;首次犯错
p->next=s;
return h;
}
nodetype* dele(nodetype*h,int i)
{
nodetype* p,* q;
p=find(h,i-1);
q=p->next;
p->next=q->next;
free(q);
return h;
}
/*void dispose(nodetype* h)//释放存储空间
{
nodetype* p,* q;
if(h->next==NULL)
free(h);
else
p=h;
q=p->next;
while(q!=0)
{
free(p);
p=q;
q=q->next;
}
free(p);
}*/