用C++创建一个递增有序的单链表
时间: 2024-05-21 15:10:12 浏览: 51
[C++]单链表的创建,合并和输出
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insert(struct Node** head, int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* current = *head;
struct Node* prev = NULL;
while (current != NULL && current->data < value) {
prev = current;
current = current->next;
}
if (prev == NULL) {
newNode->next = *head;
*head = newNode;
} else {
prev->next = newNode;
newNode->next = current;
}
}
void display(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
insert(&head, 5);
insert(&head, 3);
insert(&head, 8);
insert(&head, 1);
display(head);
return 0;
}
阅读全文