构建正序链表:C语言实现链表正序输出方法
include
include
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)->data >= newNode->data) {
newNode->next = *head;
*head = newNode;
}
else {
struct Node* current = *head;
while (current->next != NULL && current->next->data < newNode->data) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main() {
struct Node* head = NULL;
insert(&head, 5);
insert(&head, 10);
insert(&head, 7);
insert(&head, 3);
insert(&head, 1);
printf("正序链表输出:");
printList(head);
return 0;
}
下载地址
用户评论