PS:记得去年我都没有上过课,没事干复习一下第一章,仅此一章。
#define MaxSize 50
typedef struct
{
ElemType data[MaxSize];
int len;
}List;
#define MaxSize 50
typedef struct
{
ElemType *data; //是一个地址,没有确切的空间,所以在使用时,需要动态申请空间
int len;
}List;
C L.data=(Elemtype*)malloc(sizeof(ElemType)*InitSize);
C++ = new ElemType[InitSize];
数组下标0,顺序表下标1。
bool insertt(List &L,int i,ElemType e)
{
if((i<1||i>L.len+1)||L.len>=MaxSize)
return 0;
for(int j=L.len;j>=i;j--)
L.data[j]=L.data[j-1];
L.data[i-1]=e;
L.len++;
return 1;
}
bool Delete(List &L,ElemType e)
{
if(i<1||i>L.len)
return 0;
e=L.data[i-1];
for(int j=i;j<L.len;j++)
L.data[j-1]=L.data[j];
L.len--;
return 1;
}
int Locate(List &L,int i,ElemType e)
{
for(int i=0;i<L.len;i++)
{
if(L.data[i]==e)
return i+1;
}
return 0;
}
typedef struct node
{
ElemType data;
struct node *nextt;
}node,*List;
第一种:head头指针为NULL时
第二种:head-->next为NULL时(头结点的next的域为空)
注意:头指针指向头结点。(头指针,是指向链表头的指针;头结点,是链表头指针指向的节点。)
时间复杂度:O(N)
关键代码:
s->next=L->next
L->next=s
List headinsert(List &L)
{
node *s; //当前插入的结点
int x; //所插入的数据
//初始化头结点
L=(List)malloc(sizeof(node));
L->next=NULL;
cin>>x;
while(x!=9999) // 插入多个结点
{
s=(node*)malloc(sizeof(node));//创建空间
s->data=x;
s->next=L->next;
L->next=s;
cin>>x;
}
return L;
}
关键代码:
tail->next=s
tail=s
List tailinsert(List &L)
{
int x; //所插入的数据
L=(List)malloc(sizeof(node));
node *s,*r=L;
cin>>x;
while(x!=9999) // 插入多个结点
{
s=(node*)malloc(sizeof(node));//创建空间
s->data=x;
tail->next=s;
tail=s;
cin>>x;
}
tail->next=NULL;
return L;
}
node *get(List L,int i)
{
int j=1;//从1开始
node *p=L->next;//头结点不保存元素,所以从下一个开始
if(i==0) //代表是头结点
return L;
if(i<1)
return NULL;
while(p&&j<i) //遍历单链表
{
p=p->next;
j++;
}
return p;//找到了,返回该结点
}
node *Locate(List L,EleType e)
{
node *p=L->next;
while(p!=NULL&&p->data!=e) // 为空说明遍历完成
p=p->next;
return p;
}
和头插法不一样的是:需要知道位置。
p=get(L,i-1);
s->next=p->next;
p->next=s;
首先要判断是否是在头部插入的。
s->next=head
head=s
原文:https://www.cnblogs.com/OFSHK/p/13169987.html