#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <stdlib.h>
using namespace std;
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define List_init_size 100
#define LISTINCREMENT 10
typedef int ElemType;
typedef int Status;
typedef struct
{
ElemType *elem;
int length;
int listsize;
} SqList;
Status initlist(SqList &L) // 建立一个空的链表
{
L.elem=(int *)malloc(sizeof(int)*List_init_size);
if(!L.elem)
exit(OVERFLOW);
L.length = 0;
L.listsize = List_init_size;
return OK;
}
Status ListInsert_Sq(SqList &L, int i, ElemType e) // 里面有重新分配内存的地方!!!
{
ElemType *newbase,*p,*q;
if (i<1||i>L.length+1) return ERROR;
if (L.length>=L.listsize)
{
newbase = (ElemType *)realloc(L.elem, (L.listsize+LISTINCREMENT)*sizeof(ElemType)) ; // 重新分配内存!!!!!!!
if (!newbase) exit (OVERFLOW);
L.elem = newbase;
L.listsize=L.listsize+LISTINCREMENT;
}
q=&(L.elem[i-1]);
for (p=&(L.elem[L.length-1]); p>=q; --p) *(p+1)=*p;
*q=e;
L.length++;
return OK;
}
Status ListDelete_Sq(SqList &L, int i, ElemType &e) // 删除链表内的元素
{
ElemType *p,*q;
if ((i<1)||i>L.length) return ERROR;
p=&L.elem[i-1];
e=*p;
q=L.elem+L.length-1;
for (++p; p<=q; ++p)
*(p-1)=*p;
--L.length;
return OK;
} //ListDelete_Sq
int main()
{
SqList L;
initlist(L);
int n;
cout<<"请输入要插入几个数:";
cin>>n;
int i,e;
cout<<"输入的数为: ";
for(i = 1;i <= n;++i)
{
cin>>e;
ListInsert_Sq(L,i,e);
}
cout<<"现在的链表为:";
for(i = 0;i < L.length;++i)
cout<<" "<<L.elem[i];
cout<<endl;
cout<<"请输入要插入的的位置: ";
cin>>i;
cout<<"请输入要插入的元素: ";
cin>>e;
ListInsert_Sq(L,i,e);
cout<<"插入完后的链表为:";
for(i = 0;i <L.length;++i)
cout<<" "<<L.elem[i];
cout<<endl;
cout<<"请输入要删除的元素位置:";
cin>>i;
ListDelete_Sq(L,i,e);
cout<<"删除的元素为:"<<e<<endl;
cout<<"删除完以后的链表为:";
for(i = 0;i < L.length;++i)
cout<<" "<<L.elem[i];
cout<<endl;
return 0;
}
初谈链表--链表的创建与增加元素删除元素,重新申请长度!
最新推荐文章于 2023-09-19 09:28:34 发布