您的位置:首页 > 其它

带头结点的链表实现线性表的基本操作

2013-06-21 22:46 597 查看
带头结点的链表和不带头结点的链表之间存在一定的区别

1.phead是从第一个开始循环(第一个数据元素), 带头结点的phead从第二个结点开始循环(第一个数据元素)

2.不带头结点的链表在插入和删除操作的时候需要把插入的第一个位置和其他位置分开讨论,带头结点的链表在插入和删除的时候操作一致

主要原因是不带头结点的链表phead和phead->next赋值的时候不一致的情况造成的。

所以带头结点的链表比不带头结点的链表方便

所有的操作都是针对元素本身,所以需要找到或者给出元素所在的位置i,才能对其进行操作,插入和删除找到的是i-1

若是对整个结构操作,则需要利用循环,同样利用到位置i或者指针p对数据元素的操作。

//线性表链式存储

//链表结点
struct LNode
{
elemtype data;
struct LNode *next;
};

//1.初始化带有头结点的链表
int InitList_L(LNode *pHead)
{
pHead = (LNode*)malloc(sizeof(LNode));
if (!pHead)
{
return ERROR;
}
pHead->next = NULL;
return OK;
}

//2.建立链表的方式之一,通过循环调用插入链表结点函数

int CreatList_L(LNode *pHead)
{

if (!pHead)
{
return ERROR;
}

for (int i = 3;i > 0;--i)
{
LNode *p = (LNode*)malloc(sizeof(LNode));
scanf("%d",&(p->data));
p->next = pHead->next;
pHead->next = p;
}
return OK;
}

//3.插入结点
int ListInsert_L(LNode *pHead,int i,elemtype e)
{
LNode *p = pHead;
int j = 0;
while (p && j < i-1)
{
p = p->next;
j++;
}
LNode *s = (LNode *)malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
return OK;
}
int CreatList_L2(LNode *pHead)
{

LNode *p = pHead ;
int e = 0;
for (int i = 2;i > 0;--i)
{
scanf("%d",&e);
ListInsert_L(p,1,e);
p = p->next;
}
return OK;
}

//4.删除链表结点
int DeleteList_L(LNode *pHead,int i)
{
LNode *p = pHead;
int j = 0;
while (p && j < i-1)
{
p = p->next;
++j;
}
LNode *q = p->next;
p->next = q->next;
free(q);
return OK;
}
//5.清空或者摧毁链表(包括头结点)
//直接清除所有节点
int ClearList(LNode *pHead)
{
LNode *pTemp= NULL;
while(pHead)
{
pTemp = pHead ->next;
free(pHead);
pHead = pTemp;
}
return  OK;
}
//间接清空所有结点
int ClearList_L(LNode *pHead)
{
//删除数据元素结点
while (pHead->next)
{
DeleteList_L(pHead,1);
}
free(pHead);//最后删除头结点
return OK;
}

//6.取得线性表的第i个数据元素
int GetList_L(LNode *pHead,int i)
{
int j = 1;
LNode *p = pHead->next;
while(p && j < i)
{
p->next;
}
//return p;//返回位置指针
return p->data;//返回数据元素

}
//7.后继

int NextElem_L(LNode *pHead,int i)
{
int j = 1;
LNode *p = pHead->next;
while(p && j < i)
{
p->next;
}

return p->next->data;//返回后继指针
}

//8.前驱
int PriorElem_L(LNode *pHead,int i)
{
int j = 0;
LNode *p = pHead;
while(p && j < i -1)
{
p->next;
}

return p->next->data;//返回后继指针
}

//9.长度
int ListLength(LNode *pHead)
{
int length = 0;
for (LNode * p = pHead->next;p != NULL;)
{
length++;
p=p->next;
}
return length;
}
//10.输出
void ListDisplay(LNode *pHead)
{

for (LNode * p = pHead->next;p != NULL;)
{
printf("%d ",p->data);
p=p->next;
}

}

int main()
{
LNode *pHead =NULL;
//InitList_L(pHead);
pHead = (LNode*)malloc(sizeof(LNode));
pHead->next = NULL;
if (!pHead)
{
return ERROR;
}
CreatList_L(pHead);
ListDisplay(pHead);
ListInsert_L(pHead,2,190);
printf("\n");
ListDisplay(pHead);
printf("\n");
DeleteList_L(pHead,3);
ListDisplay(pHead);
return OK;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐