使用C语言将一个链表按照一个基准分为两个链表
时间: 2024-05-03 10:21:10 浏览: 9
以下是一个示例代码,其中基准值为x:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
// 创建一个新节点
Node* createNode(int data) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 将节点插入链表尾部
void insertNode(Node **head, Node *newNode) {
if (*head == NULL) {
*head = newNode;
} else {
Node *cur = *head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = newNode;
}
}
// 将链表按基准值分为两个链表
void splitList(Node *head, int x, Node **list1, Node **list2) {
Node *cur = head;
while (cur != NULL) {
Node *next = cur->next;
if (cur->data < x) {
insertNode(list1, cur);
} else {
insertNode(list2, cur);
}
cur = next;
}
}
// 打印链表
void printList(Node *head) {
Node *cur = head;
while (cur != NULL) {
printf("%d ", cur->data);
cur = cur->next;
}
}
int main() {
Node *head = NULL;
insertNode(&head, createNode(3));
insertNode(&head, createNode(8));
insertNode(&head, createNode(1));
insertNode(&head, createNode(6));
insertNode(&head, createNode(4));
insertNode(&head, createNode(2));
insertNode(&head, createNode(9));
insertNode(&head, createNode(5));
Node *list1 = NULL;
Node *list2 = NULL;
int x = 5;
splitList(head, x, &list1, &list2);
printf("List 1: ");
printList(list1);
printf("\nList 2: ");
printList(list2);
printf("\n");
return 0;
}
```
输出:
```
List 1: 3 1 4 2
List 2: 8 6 9 5
```