线性表 —— 带头结点单链表(C语言)

线性表之链表操作

1. 结构定义

typedef struct LNode* LinkedList;

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

2. 链表初始化

bool InitLinkedList(LinkedList &L)
{
    
    
    L = (LinkedList)malloc(sizeof(struct LNode));
    if(!L) exit(OVERFLOW);
    L->next = NULL;
    return success;
}

3. 在链表指定位置插入元素

/*
    @description: 在链表指定位置插入元素
 */
bool LinkedListInsert(LinkedList &L, int index, ElemType e)
{
    
    
    LNode* p = L; int i = 1;
    while(p && i < index)
    {
    
    
        p = p->next;
        i++;
    }
    if(!p || i > index) return failed;
    LNode* s = (LNode* )malloc(sizeof(LNode));
    s->data = e;
    s->next = p->next;
    p->next = s;
    return success;
}

4. 删除链表指定位置的元素

/*
    @description: 删除链表指定位置的元素
 */
bool LinkedListDelete(LinkedList &L, int index)
{
    
    
    LNode* p = L; int i = 1;
    while(p->next && i < index)
    {
    
    
        p = p->next;
        i++;
    }
    if(!p->next || i > index) return failed;
    LNode* s = p->next;
    p->next = s->next;
    free(s);
    return success;
}

5. 获取指定位置元素

/*
    @description: 获取链表指定位置元素
 */
bool GetLinkedListElem(LinkedList L, int index, ElemType &e)
{
    
    
    LNode* p = L->next; int i = 1;
    while(p && i < index)
    {
    
    
        p = p->next;
        i++;
    }
    if(!p || i > index)return failed;
    e = p->data;
    return success;
}

6. 获取指定元素在链表中的位置

/*
    @description: 获取链表指定位置元素
    @return: 查询不到元素e则返回-1, 反之返回位置index
 */
int LocateLinkedListElem(LinkedList L, ElemType e)
{
    
    
    LNode* p = L->next; int i = 1;
    while(p && p->data != e)
    {
    
    
        p = p->next;
        i++;
    }
    if(p)return i;
    return -1;
}

7. 从头到尾遍历链表

void ReadLinkedList(LinkedList &L)
{
    
    
    LNode* p = L->next;
    while(p)
    {
    
    
        printf("%d\n",p->data);
        p = p->next;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45830383/article/details/114369147
今日推荐