概率论课上闲来无事,顺手把数据结构实验写了,
要求如下
一、实验目的
熟悉某种数据结构在计算机上实现的方法。掌握单链表的定义、创建、插入、删除、遍历等基本操作的实现。体会单链表操作、有序表插入、删除的一般方法。
二、实验内容问题描述:
已知递增有序的单链表A,编写算法实现向A中插入或删除一个元素,并保持A的有序性。
实验要求:结点的数据均为整型。若表中已经存在此元素,则不插入
代码如下
样例输入;
1 3 5 7 9 0
2 4 6 7 8 0
6
样例输出;
9 7 5 3 1
9 8 7 6 5 4 3 2 1
9 8 7 5 4 3 2 1
#include<iostream>//按序插入
#define ERROR -1
#define exist 1
#define OK 0
using namespace std;
//Author Spark
typedef struct LNode
{
int data;
struct LNode *next;
}
LNode,*linklist;
void init(linklist &L)
{
L = (linklist)malloc(sizeof(LNode));
L->next = NULL;
}
void Create_linklist(linklist &L)
{
linklist p;
int data;
while(cin>>data&&data != 0)
{
p = (linklist)malloc(sizeof(LNode));
p->data = data;
p->next = L->next;
L->next = p;
}
}
int lenlist(linklist L)
{
int cnt = 0;
while(L->next)
{
cnt++;
L=L->next;
}
return cnt;
}
int searchList(linklist L,int n)
{
int cnt = 0;
while(L->next)
{
cnt ++;
if(L->next->data == n){
return cnt;
break;
}
L=L->next;
}
return 0;
}
int insertElem(linklist &L,int n)
{
if(searchList(L,n))
return exist;
linklist tmp = L;
do tmp = tmp->next;
while(tmp&&tmp->next->data > n);
linklist s = new LNode;
s->data = n;
s->next = tmp->next;
tmp->next = s;
return OK;
}
void TranverseList(linklist L)
{
while(L->next)
{
cout<<L->next->data<<" ";
L=L->next;
}
cout<<endl;
}
int delElem(linklist &L,int n)
{
int cnt = searchList(L,n)-1;
if(cnt==-1)return ERROR;
linklist ptr=L->next;
linklist pre=L;
while(cnt--&&ptr)
{
pre=pre->next;
ptr=ptr->next;
}
if(ptr==NULL&&cnt>0)return ERROR;
pre->next=ptr->next;
free(ptr);
return OK;
}
int main()
{
linklist L;
init(L);
Create_linklist(L);
TranverseList(L);
int n;
while(cin>>n&&n!=0)
insertElem(L,n);
TranverseList(L);
int tmp;
cin>>tmp;
delElem(L,tmp);
TranverseList(L);
return 0;
}
心得体会
手机打代码真难受