3. 线性表的链式结构

图片

一、链表的声明

typedef struct 
{
    ElemType data;
    struct LNode *next;
}LNode, *LinkList;

二、头插法

  1. s->next = L->next
  2. L->next = s
//头插法
void CreateListF(LinkNode *&L,ElemType a[],int n){
    L=(LinkNode *)malloc(sizeof(LinkNode));
	L->next=NULL;
    LinkNode *s;
	for(int i =0; i < n; i++){
		s=(LinkNode *)malloc(sizeof(LinkNode));
		s->data = a[i];
		s->next = L->next;
		L->next = s;
	}
}

三、尾插法

  1. r = L
  2. s->next = r->next
  3. r->next = r
  4. r = r->next
//尾插法
void CreateListR(LinkNode *&L,ElemType a[],int n){
    L=(LinkNode *)malloc(sizeof(LinkNode));
	L->next=NULL;
    LinkNode *s,*r;
	r = L;
	for(int i =0; i < n; i++){
		s=(LinkNode *)malloc(sizeof(LinkNode));
		s->data = a[i];
		s->next = r->next;
		r->next = s;
		r = r->next;
	}
}

四、按序号查找

//按序号查找
LinkNode *GetElem(LinkNode *&L, int i){
	int j = 1;
	LinkNode *p = L;
	if(i == 0)
		return L;//返回头节点
	if(i<1)
		return NULL;
	while(p && j<i){ //p是否为NULL判断是否到链表尾
		p = p->next;
		j++;
	}
	return p;
}

五、插入

bool ListInsert(LinkNode *&L,int i,ElemType e)
{
	LinkNode* p = GetElem(L,i-1);//获取第i-1号节点
	LinkNode *s;
    
	s->data = e;
	s->next = p->next;
	p->next = s;
}

六、删除

bool ListDelete(LinkNode *&L,int i,ElemType &e)
{
	LinkNode* pre = GetElem(L,i-1);//获取第i-1号节点
	LinkNode* p = pre->next;//第i号
	if(pre == NULL)
		return false;
	e = p->data;
	pre->next = p->next;
	free(p);
	return true;
}

七、销毁表

void DestroyList(LinkNode *&L)
{
	LinkNode *pre=L,*p=pre->next;
	while (p!=NULL)
	{	free(pre);
		pre=p;
		p=pre->next;
	}
	free(pre);
}

八、测试

void DispList(LinkNode *L)
{
	LinkNode *p=L->next;
	while (p!=NULL)
	{	printf("%d ",p->data);
		p=p->next;
	}
	printf("
");
}

int main() {
	int a[5] = { 1, 2, 3, 4, 5 };
	LinkNode* ln;
	CreateListR(ln, a, 5);
	DispList(ln);
}

输出结果:

1 2 3 4 5

原文地址:https://www.cnblogs.com/theory/p/13338754.html