头部互动开始 -->

笔试题:设计一个算法删除单链表L(有头结点)中的一个最小值结点

数据结构——笔试题

设计一个算法删除单链表L(有头结点)中的一个最小值结点

/********************************************************************************************************
 *  file name:  zuoye.c
 *  author   :  15070884254@163.com
 *  date     :  2024/04/22
 *  function :  对链表进行相应的初始化
 *  note     :  None
******************************************************************************************************/

// 指的是单向链表中的结点有效数据类型,用户可以根据需要进行修改
typedef int DataType_t;

// 构造链表的结点,链表中所有结点的数据类型应该是相同的
typedef struct LinkedList
{
  DataType_t data;         // 结点的数据域
  struct LinkedList *next; // 结点的指针域

} LList_t;

// 创建一个空链表,空链表应该有一个头结点,对链表进行初始化
LList_t *LList_Create(void)
{
  // 1.创建一个头结点并对头结点申请内存
  LList_t *head = (LList_t *)calloc(1, sizeof(LList_t));
  if (NULL == head)
  {
    perror("Calloc memory for Head is Failed");
    exit(-1);
  }

  // 2.对头结点进行初始化,头结点是不存储有效内容的!!!
  head->next = NULL;

  // 3.把头结点的地址返回即可
  return head;
}
/********************************************************
*  func name:  DelMinNode
*  author   :  15070884254@163.com
*  date     :  2024/04/22
*  function :  删除单链表L(有头结点)中的一个最小值结点
*  note     :  None
*  Copyright (c)  2023-2024   cececlmx@126.com   All right Reserved
*********************************************/

bool DelMinNode(LList_t *head,DataType_t data)
{ 
  LList_t *findmin = NULL;
  LList_t *findend = NULL;
  LList_t *findit = NULL;
  //判断链表是否为空,如果为空,则删除失败
	if (NULL == head->next)
	{
		return false;
	}
	
  //使用三个指针指向首结点

   findmin=head->next;
   findend=head->next;
   findit=head;
  //遍历链表寻找最小值结点
  while(findend->next){
    if(findmin->data < findend->next->data){
      findend=findend->next;
    }
    else{
     findmin=findend->next;  //同步两个指针的位置,继续遍历
     findend=findend->next;
    } 
  }
  //遍历找出findmin前驱
  while(findit->next!=findmin){
      findit=findit->next;
    }
	
    findit->next=findmin->next;
    findmin=NULL;
    free(findmin);
    return true;
}
posted @ 2024-04-22 22:23  罗天天  阅读(21)  评论(1编辑  收藏  举报