编程完成单链表的建立、遍历、插入、删除、查找、排序、合并、归并等算法功能及实现。
代码
#include<iostream>
#include<string.h>
#include<ctype.h>
#include<malloc.h>
#include<limits.h>
#include<stdio.h>
#include<stdlib.h>
#include<io.h>
#include<process.h>
using namespace std;
#define TURE 1
#define FLASE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef int Status;
typedef int Boolean;
typedef int Elemtype;
struct LNode //链表结构
{
Elemtype data;
Elemtype len;
LNode *next;
};
typedef struct LNode *LinkList;
Status GetElem(LinkList L,int n,Elemtype &e) //获取表中n位置元素并用e返回
{
LinkList p=L;
if (n<=0||n>L->len) return ERROR;
for(int i=1;i<=n;i++) p=p->next;
e=p->data;
return OK;
}
int LocateElem(LinkList L,Elemtype e)
{
LinkList p=L->next;
int i=1;
while(p) {
if(p->data==e) return i; p=p->next;i++;}
return 0;
}
Status CreatLink1(LinkList &L,int n) //正序创建链表
{
L=(LinkList)malloc(sizeof(LNode));
if(!L) exit(OVERFLOW);
L->next=NULL;
L->len=0;
LinkList p,q;
p=L;
for(int i=1;i<=n;i++)
{
q=(LinkList)malloc(sizeof(LNode));
cin>>q->data;
p->next=q;
p=p->next;
L->len++;
}
p->next=NULL;
return OK;
}
Status CreatLink2(LinkList &L,int n) //逆序创建链表
{
L=(LinkList)malloc(sizeof(LNode));
if(!L) exit(OVERFLOW);
L->len=0;
L->next=NULL;
LinkList p,q;
for(int i=1;i<=n;i++)
{
q=(LinkList)malloc(sizeof(LNode));
cin>>q->data;
p=L->next;
q->next=p;
L->next=q;
L->len++;
}
return OK;
}
Status ListTraverse(LinkList L) //遍历表
{
LinkList p=L->next;
while(p) {
cout<<p->data