删除或插入无头单链表的非尾结点

    xiaoxiao2021-03-25  51

    解决方案为:

    一般情况我们想要删除一个结点,我们需要直到上上个位置,而现在并没有,所以我们只需要把下一位置值赋予当前位置,并删除下个位置,并将当前位置指向下下个位置。

    代码实现如下:

    1.创建结构体

    typedef struct Node { DataType data; struct Node* next; }Node, *pNode;

    2.创建结点

    pNode BuyNode(DataType d) { pNode pnode = (pNode)malloc(sizeof(Node)); if(pnode == NULL) { perror("创建失败\n"); return NULL; } pnode->data = d; pnode->next = NULL; return pnode; }

    3. 删除无头非尾结点

    void EraseNotTail(pNode pos) //删除 { assert(pos->next != NULL); pNode tmp = NULL; tmp = pos->next; //要释放的空间 pos->data = pos->next->data; //值传递 pos->next = pos->next->next; //改变位置指向 free(tmp); } //4. 插入一结点 void IsertFrontNode(pNode pos, DataType d) //插入 { pNode newnode = BuyNode(d); int tmp = 0; newnode->next = pos->next; //将新点和当前位置指向同一下一位置 pos->next = newnode; tmp = pos->data; pos->data = pos->next->data; pos->next->data = tmp; }

    转载请注明原文地址: https://ju.6miu.com/read-37160.html

    最新回复(0)