线性表-TwoLinkList(双链表)

知识点
   1:循环双链表尾结点指向头结点
typedef struct TWONode
{
    int data;
    pNode *prev,*next;
} pNode;
复制代码
int main(int argc, char const *argv[])
{
    int n, element, flag;
    pNode *head, *last;
    /***************************************************************/
    printf("Please input the size of the list:");
    scanf("%d", &n);
    last = InitList(&head, n);//初始化链表并赋值,返回尾节点last
    printf("%d %d \n", head->next->data, last->data); //打印为第一个元素和最后一个元素
    PrintList(head);
    /***************************************************************/
    flag = SearchList(head); //搜索某个值并删除节点
    if (flag > 0 && flag <= n)
    {
        DelNumqList(&head, flag);
        PrintList(head);
    }
    else
        printf("Element does not exist, cannot be deleted\n");
    /***************************************************************/
    DeleteList(&head);//清空列表
    PrintList(head);
    return 0;
}
复制代码

初始化双链表尾插法

复制代码
pNode *InitList(pNode **head,int n)
{
    pNode *p,*s;
    *head=(pNode *)malloc(sizeof(pNode));
    if(*head==NUll)
    {
        return 0;
    }
    *head->next=NULL;
    *head->prev=NULL;
    p=*head;
    int i;
    for(i=0;i<n;++i)
    {
        s=(pNode *)malloc(sizeof(pNode));
        if(s==0)return 0;
        printf("Input the value of the %dth node:", i + 1);
        scanf("%d",&s->data);
        s->next=NULL;
p
->next=s; s->prev=p; p=s; } return p; }
复制代码

遍历打印

复制代码
void prinList(pNode *head)
{
    pNode *p;
    p=head->next;
    if(head->next==NULL)
    {
        return 0;
    }
    while(p!=NULL)
    {
        printf("%d ",p->data);
        p=p->next;
    }
}
复制代码

请空链表

复制代码
void delectList(pNode **head)
{
    pNode *p;
    while(*head->next!=NULL)
    {
        p=*head;
        p->next->prev=NULL;
        *head=p->next;
        free(p);
    }
}
复制代码

查找

复制代码
int searchList(pNode *head)
{
    int number;
    printf("Values are about to be deleted:");
    scanf("%d",&number);
    pNode *p;
    p=head->next;
    while(p!=NULL)
    {
        if(p->data==number)
        {
            return number;
        }
        p=p->next;
    }
    return 0;
}
复制代码

删除元素

复制代码
void delNumList(pNode **head,int n)
{
    int i;
    pNode *p;
    p=*head->next;
    for(i=1;i<n;++i)
    {
        p=p->next;
    }
    if(p->next==NULl)//如果p是尾节点则直接将前驱节点指向NULL
    {
        p->prev->next==NULL;
        free(p);
    }
    else//令p的前驱节点和后驱节点相互指向即可
    {
        p->next->prev=p->prev;
        p->prev->next=p->next;
        free(p);
    }
}
复制代码

 

posted on   Y-flower  阅读(42)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示