Linear list-singly linked list with lead node (C language)

Linked list operation of linear list

1. Structure definition

typedef struct LNode* LinkedList;

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

2. Linked list initialization

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

3. Insert an element at the specified position in the linked list

/*
    @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. Delete the element at the specified position of the linked list

/*
    @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. Get the specified position element

/*
    @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. Get the position of the specified element in the linked list

/*
    @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. Traverse the linked list from beginning to end

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

Guess you like

Origin blog.csdn.net/qq_45830383/article/details/114369147