本题代码为
void deletemin(linklist* L)//找到最小值并删除
{lnode* p = (*L)->next, * pre = *L;lnode* s = p,*spre=pre;while (p != NULL)//找到最小值{if (p->data < s->data){s = p;spre = pre;}p = p->next;pre = pre->next;}p = s->next;spre->next = p;free(s);
}
完整测试代码
#include<stdio.h>
#include<stdlib.h>
typedef struct lnode
{int data;struct lnode* next;
}lnode,*linklist;
int n = 4;
int a[4] = { 1,2,3,4 };
void buildlinklist(linklist* L)
{*L = (lnode*)malloc(sizeof(lnode));(*L)->next = NULL;lnode* s = *L, * r = *L;int i = 0;for (i = 0; i < n; i++){s = (lnode*)malloc(sizeof(lnode));s->data = a[i];s->next = r->next;r->next = s;r = s;}r->next = NULL;
}
void deletemin(linklist* L)
{lnode* p = (*L)->next, * pre = *L;lnode* s = p,*spre=pre;while (p != NULL)//找到最小值{if (p->data < s->data){s = p;spre = pre;}p = p->next;pre = pre->next;}p = s->next;spre->next = p;free(s);
}
void print(linklist* L)
{lnode* p = (*L)->next;while (p != NULL){printf("%d", p->data);p = p->next;}
}
int main()
{linklist L;buildlinklist(&L);printf("原始单链表为:");print(&L);deletemin(&L);printf("\n删除最小值后的单链表为:");print(&L);return 0;
}