用c语言编写【头指针型】的单链表相关算法: 1、用头插法建表; 2、输出单链表 3、给定h1,将其中的所有偶数结点摘除,依次【尾插】插入h2 4、给定h,找到其中最大值结点,将其摘除,插入h之前,并返回h
时间: 2024-09-29 08:01:43 浏览: 30
在C语言中,我们可以使用结构体表示链表节点,并通过头指针(通常称为`head`)来操作整个链表。以下是针对你所列举的四个任务的简单示例:
1. **用头插法建表**:
```c
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createList(int arr[], int size) {
Node* head = NULL;
for (int i = 0; i < size; i++) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = arr[i];
newNode->next = head;
head = newNode;
}
return head;
}
```
2. **输出单链表**:
```c
void printList(Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
```
3. **给定h1,将其中所有偶数结点摘除并尾插到h2**:
```c
Node* removeEvenFromList(Node* h1, Node* h2) {
if (h1 == NULL || h2 == NULL)
return h1;
// 移动h1的奇数结点到h2
while (h1 != NULL && h1->next != NULL) {
if (h1->next->data % 2 != 0) {
Node* temp = h1->next;
h1->next = h1->next->next;
temp->next = h2->next;
h2->next = temp;
} else {
h1 = h1->next;
}
}
// 将剩余的h1连接到h2之后
if (h1 != NULL)
h2->next = h1;
return h2->next;
}
```
4. **给定h,找到最大值结点并移除后插入到h之前**:
```c
Node* insertMaxBefore(Node* h) {
Node* maxNode = h;
Node* current = h->next;
while (current != NULL) {
if (current->data > maxNode->data) {
maxNode = current;
}
current = current->next;
}
// 删除最大值结点
if (maxNode != h) {
if (h->next == maxNode) {
h->next = maxNode->next;
} else {
Node* prevMax = h;
while (prevMax->next != maxNode) {
prevMax = prevMax->next;
}
prevMax->next = maxNode->next;
}
free(maxNode); // 释放最大值结点的空间
}
// 将最大值移到最前面
maxNode->next = h;
h = maxNode;
return h;
}
```
阅读全文