c语言:单链表按奇偶序号拆分为两个链表
时间: 2023-07-12 08:20:18 浏览: 172
将一个结点值自然数的单链表拆分为两个单链表,原表中保留值为偶数的结点,而值为奇数的结点按它们在原表中的相对次序组成一个新的单链表
以下是C语言的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
//定义链表结点结构体
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* createList(int arr[], int n) {
struct ListNode *head, *p, *q;
head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next = NULL;
p = head;
for (int i = 0; i < n; i++) {
q = (struct ListNode*)malloc(sizeof(struct ListNode));
q->val = arr[i];
q->next = NULL;
p->next = q;
p = q;
}
return head;
}
void printList(struct ListNode* head) {
struct ListNode* p = head->next;
while (p) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
}
struct ListNode* splitList(struct ListNode* head) {
struct ListNode *oddHead, *evenHead, *p, *q;
oddHead = (struct ListNode*)malloc(sizeof(struct ListNode));
evenHead = (struct ListNode*)malloc(sizeof(struct ListNode));
oddHead->next = NULL;
evenHead->next = NULL;
p = oddHead;
q = evenHead;
struct ListNode* cur = head->next;
int count = 1;
while (cur) {
if (count % 2 == 1) {
p->next = cur;
p = cur;
} else {
q->next = cur;
q = cur;
}
cur = cur->next;
count++;
}
p->next = NULL;
q->next = NULL;
head->next = oddHead->next;
return evenHead;
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int n = sizeof(arr) / sizeof(int);
struct ListNode* head = createList(arr, n);
printf("Original list: ");
printList(head);
struct ListNode* evenHead = splitList(head);
printf("Odd index list: ");
printList(head);
printf("Even index list: ");
printList(evenHead);
return 0;
}
```
这个算法的实现思路是:遍历原链表,将奇数序号的结点连接到一个新的链表上,将偶数序号的结点连接到另一个新的链表上。最后,将原链表的表头指向奇数序号链表的表头,返回偶数序号链表的表头。
同样的,这个算法需要手动创建两个新的链表,分别保存奇数序号结点和偶数序号结点。最后,由于原链表的表头改变了,需要将原链表的表头指向奇数序号链表的表头。
阅读全文