#include <iostream> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* insert(ListNode* head, int x) { ListNode* prev = NULL; ListNode* curr = head; while (curr != NULL && curr->val <= x) { prev = curr; curr = curr->next; } ListNode* node = new ListNode(x); if (prev == NULL) { node->next = head; return node; } else { node->next = prev->next; prev->next = node; return head; } } void printList(ListNode* head) { while (head != NULL) { cout << head->val << " "; head = head->next; } cout << endl; } int main() { int n, x; cin >> n; ListNode* head = NULL; for (int i = 0; i < n; i++) { int val; cin >> val; head = insert(head, val); } cin >> x; head = insert(head, x); printList(head); return 0; } 用c语言实现
时间: 2024-01-26 17:01:39 浏览: 143
以下是使用C语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode* next;
};
struct ListNode* insert(struct ListNode* head, int x) {
struct ListNode* prev = NULL;
struct ListNode* curr = head;
while (curr != NULL && curr->val <= x) {
prev = curr;
curr = curr->next;
}
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = x;
if (prev == NULL) {
node->next = head;
return node;
} else {
node->next = prev->next;
prev->next = node;
return head;
}
}
void printList(struct ListNode* head) {
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
int main() {
int n, x;
scanf("%d", &n);
struct ListNode* head = NULL;
for (int i = 0; i < n; i++) {
int val;
scanf("%d", &val);
head = insert(head, val);
}
scanf("%d", &x);
head = insert(head, x);
printList(head);
return 0;
}
```
这个C语言版本的代码与C++版本的代码非常相似,只是语法和一些细节上有所不同。
阅读全文