在带头结点单链表中查找最小值,将新输入的值插入到最小值前面,输出插入新元素后的单链表各元素。c语言
时间: 2024-03-23 11:19:59 浏览: 79
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建带头结点的单链表
Node* createList() {
Node* head = (Node*)malloc(sizeof(Node));
head->next = NULL;
return head;
}
// 在链表的最小值前插入新节点
void insertBeforeMin(Node* head, int num) {
Node* p = head->next;
Node* pre = head;
Node* minNode = p;
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = num;
newNode->next = NULL;
// 找到链表中的最小值节点
while (p != NULL) {
if (p->data < minNode->data) {
minNode = p;
pre = pre->next;
}
else {
pre = p;
}
p = p->next;
}
// 在最小值节点前插入新节点
newNode->next = minNode;
pre->next = newNode;
}
// 输出链表中的元素
void printList(Node* head) {
Node* p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Node* head = createList();
int num, i;
printf("请输入链表中的元素(以0结束):\n");
scanf("%d", &num);
while (num != 0) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = num;
newNode->next = NULL;
Node* p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = newNode;
scanf("%d", &num);
}
printf("原始链表各元素为:\n");
printList(head);
printf("请输入要插入的新元素:\n");
scanf("%d", &num);
insertBeforeMin(head, num);
printf("插入新元素后的链表各元素为:\n");
printList(head);
return 0;
}
阅读全文