码迷,mamicode.com
首页 > 其他好文 > 详细

线性表带头结点的单链表的链式表示和实现

时间:2015-07-19 18:06:27      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:c   数据结构   考研   计算机专业   

线性表的单链表存储结构

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

带有头结点的单链表的12个基本操作

void InitList(LinkList &L){
    L = (LinkList)malloc(sizeof(LNode));
    if (!L)exit(OVERFLOW);
    L->next = NULL;
}

void DestroyList(LinkList &L){
    LinkList q;
    while (L){
        q = L->next;
        free(L);
        L = q->next;
    }
}

void ClearList(LinkList &L){
    LinkList q = L->next;
    L->next = NULL;
    DestroyList(q);
}

Status ListEmpty(LinkList L){
    if (L->next == NULL)return FALSE;
    else return TRUE;
}

int ListLength(LinkList L){
    LinkList p = L->next;
    int i = 0;
    while (p)
    {
        i++;
        p = p->next;
    }
    return i;
}

Status GetElem(LinkList L, int i, ElemType &e){
    int j = 1;
    LinkList p = L->next;
    while (p &&j <i)
    {
        j++;
        p = p->next;
    }
    if (!p || j>i)return ERROR;
    e = p->data;
    return OK;
}

int LocateElem(LinkList L, ElemType e, Status(*compare)(ElemType, ElemType)){
    int i = 1;
    LinkList p = L->next;
    while (p){
        i++;
        if (compare(p->data, e))
            return i;
        p = p->next;
    }
    return 0;
}

Status PriorElem(LinkList L, ElemType cur_e, ElemType &pre_e){
    int i = 2;
    LinkList q, p = L->next;
    while (p->next){
        q = p->next;
        if (q->data == cur_e){
            pre_e = p->data;
            return OK;
        }
        p = q;
    }
}

Status NextElem(LinkList L, ElemType cur_e, ElemType &next_e){
    LinkList p = L->next;
    while (p->next){
        if (p->data == cur_e){
            next_e = p->next->data;
            return OK;
        }
        p = p->next;
    }
    return ERROR;
}

Status ListInsert(LinkList L, int i, ElemType e){
    int j = 0;
    LinkList s, p = L;
    while (p && j < i-1)
    {
        j++;
        p = p->next;
    }
    if (!p || j > i - 1)
        return ERROR;
    s = (LinkList)malloc(sizeof(LNode));
    s->data = e;
    s->next = p->next;
    p->next = s;
    return OK;
}

Status ListDelete(LinkList L, int i, ElemType &e){
    int j = 0;
    LinkList q, p = L;
    while (p && j < i - 1)
    {
        j++;
        p = p->next;
    }
    if (!p || j > i - 1)
        return ERROR;
    q = p->next;
    e = q->data;
    p->next = q->next;
    free(q); 
    return OK;
}

void ListTraverse(LinkList L, void(*visit)(ElemType&)){
    LinkList p = L->next;
    while (p)
    {
        visit(p->data);
        p = p->next;
    }
    printf("\n");
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

线性表带头结点的单链表的链式表示和实现

标签:c   数据结构   考研   计算机专业   

原文地址:http://blog.csdn.net/zhou554291911/article/details/46956055

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!