删除带头结点链表中最小值的结点

删除带头结点链表中最小值的结点,第1张

删除带头结点链表中最小值的结点

deletemin.c

#include
#include
#include"deletemin.h"

LinkedList *create(void)
{
    LinkedList *l = malloc(sizeof(*l));
    l->first = NULL;
    l->last = NULL;
    element x;
    printf("请输入数据,以0结尾\n");
    while(1)
    {
        scanf("%d",&x);
      	if(x == 0)
        {
            break;
        }
        Node *p = malloc(sizeof(*p));
        p->data = x;
        p->next = NULL;
        if(l->first == NULL)
        {
            l->first = p;
            l->last = p;
        }
        else
        {
            //头插法
            p->next = l->first;
            l->first = p;
            /*
            	尾插法
            	l->last->next = p;
            	l->last = p;
            */
        }
    }
    return l;  
}
void deletemin(LinkedList *l)
{
    //pm记录最小值的结点,pmr指向它前面的一个结点
    Node *pm = l->first;
    Node *pmr = NULL;
    if(pm->next == NULL)
    {
        return;
    }
    else
    {
    //px和pxr用于循环
        Node *px = pm;
        Node *pxr = NULL;
        while(px)
        {
            if(px->data < pm->data)
            {
                pmr = pxr;
                pm = px;
            }
            pxr = px;
            px = px->next;
        }
        //找到后分情况删除
        if(pm == l->first)
        {
            if(l->first == l->last)
            {
                l->first = l->last = NULL;
                pm->next = NULL;
                free(pm);
            }
            else
            {
                l->first = pm->next;
                pm->next = NULL;
                free(pm);
            }
        }
        else if(pm == l->last)
        {
            pmr->next = NULL;
            l->last = pmr;
            free(pm);
        }
        else
        {
            pmr->next = pm->next;
            pm->next = NULL;
            free(pm);
        }
    }
}
void printlist(LinkedList *l)
{
    if(l == NULL)
    {
        return;
    }
    Node *p = l->first;
    while(p)
    {
        printf("%d",p->data);
        p = p->next;
    }
    printf("\n");
}

deletemin.h

#ifndef __DELETEMIN_H__
#define __DELETEMIN_H__
#define element int

typedef struct node
{
    element data;
    struct node *next;
}Node;

typedef struct LinkedList
{
    Node *first;
    Node *last;
}LinkedList;

LinkedList *create(void);
void deletemin(LinkedList *l);
void printlist(LinkedList *l);

#endif

main.c

#include
#include
#include"deletemin.h"

int main()
{
    LinkedList *l = create();
    printlist(l);
    deletemin(l);
    printlist(l);
    return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/713488.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-24
下一篇 2022-04-24

发表评论

登录后才能评论

评论列表(0条)

保存