c语言实现 1.分别输入几个非递减的数,建立两个单链表la,lb。 2.向链表la中的某一个位置i插入一个数据元素e。 3.删除链表la中某一个位序i的结点,并用e返回被删除的数据元素。 4.合并la,lb为一个链表lc,使得lc仍然按值非递减有序排列。
时间: 2023-06-03 07:02:23 浏览: 122
c语言实现单链表的操作:创建,删除,插入,反转, 排序等
4星 · 用户满意度95%
好的,这些问题都是技术/编程方面的问题,我可以为您解答。以下是关于这些问题的回答:
1. 实现方法如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* next;
} Node;
void insert(Node** head, int num) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = num;
new_node->next = NULL;
if (*head == NULL) {
*head = new_node;
return;
}
if (num < (*head)->data) {
new_node->next = *head;
*head = new_node;
return;
}
Node* curr = *head;
while (curr->next != NULL && curr->next->data < num) {
curr = curr->next;
}
new_node->next = curr->next;
curr->next = new_node;
}
void insert_at_pos(Node** head, int pos, int num) {
int i = 1;
Node* curr = *head;
while (i < pos && curr != NULL) {
curr = curr->next;
i++;
}
if (i < pos || curr == NULL) {
printf("Invalid position\n");
return;
}
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = num;
new_node->next = curr->next;
curr->next = new_node;
}
int delete_at_pos(Node** head, int pos) {
int i = 1;
Node* curr = *head;
while (i < pos && curr != NULL) {
curr = curr->next;
i++;
}
if (i < pos || curr == NULL || curr->next == NULL) {
printf("Invalid position\n");
return -1;
}
Node* to_delete = curr->next;
int data = to_delete->data;
curr->next = to_delete->next;
free(to_delete);
return data;
}
Node* merge_lists(Node* head1, Node* head2) {
Node* merged = NULL;
while (head1 != NULL && head2 != NULL) {
if (head1->data < head2->data) {
insert(&merged, head1->data);
head1 = head1->next;
} else {
insert(&merged, head2->data);
head2 = head2->next;
}
}
while (head1 != NULL) {
insert(&merged, head1->data);
head1 = head1->next;
}
while (head2 != NULL) {
insert(&merged, head2->data);
head2 = head2->next;
}
return merged;
}
void print_list(Node* head) {
Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
int main() {
Node* la = NULL;
Node* lb = NULL;
insert(&la, 1);
insert(&la, 3);
insert(&la, 5);
insert(&lb, 2);
insert(&lb, 4);
insert(&lb, 6);
insert_at_pos(&la, 2, 2);
int deleted = delete_at_pos(&la, 3);
printf("Deleted: %d\n", deleted);
Node* lc = merge_lists(la, lb);
printf("LA: ");
print_list(la);
printf("LB: ");
print_list(lb);
printf("LC: ");
print_list(lc);
return 0;
}
```
2. 此函数在上面的代码中的函数名为 insert_at_pos,实现方法已包含在上面的代码中。
3. 此函数在上面的代码中的函数名为 delete_at_pos,实现方法已包含在上面的代码中。
4. 此函数在上面的代码中的函数名为 merge_lists,实现方法已包含在上面的代码中。
阅读全文