问题描述
- c语言数据结构,求算法
- 把一个单链表LA中的奇数项和偶数项分开,分别放在两个单链表LB,LC中(要求利用原空间,头结点空间可另外开辟)
解决方案
(C语言-数据结构与算法)还原二叉树
数据结构和算法系列 - c语言归并排序法
解决方案二:
对LA进行遍历,依次把LA中的项加入LB,LC中。依靠修改原LA中项的指针实现。
解决方案三:
//输入时以-1结束#include <stdio.h>#include <stdlib.h>struct node{ int data; struct node * next;};struct node * create(){ struct node * head = NULL; struct node * p = NULL; struct node * tmp = NULL; int num; printf(""input number end -1
""); while (1) { scanf(""%d"" &num); if (num == -1) break; tmp = (struct node *)malloc(sizeof(struct node)); tmp->data = num; if (head == NULL) { head = tmp; p = head; } else { p->next = tmp; p = p->next; } } p->next = NULL; return head;}void print_link(struct node * head){ while (head) { printf(""%d "" head->data); head = head->next; } printf(""
"");}struct node ** devide_link(struct node * head){ struct node *head_even_tmp = NULL; struct node *head_odd_tmp = NULL; struct node ** head_result = (struct node * *)malloc(2 * sizeof(struct node *)); head_result[0] = NULL; head_result[1] = NULL; while (head) { if (head->data % 2) //偶数 { if (head_result[0] == NULL) { head_result[0] = head; head_even_tmp = head; } else { head_even_tmp->next = head; head_even_tmp = head_even_tmp->next; } } else //奇数 { if (head_result[1] == NULL) { head_result[1] = head; head_odd_tmp = head; } else { head_odd_tmp->next = head; head_odd_tmp = head_odd_tmp->next; } } head = head->next; } if(head_odd_tmp) head_odd_tmp->next = NULL; if(head_even_tmp) head_even_tmp->next = NULL; return head_result;}int main(){ struct node * LA = create(); struct node ** head_result = NULL; struct node *LB *LC; print_link(LA); head_result = devide_link(LA); LB = head_result[0]; LC = head_result[1]; printf(""even
""); print_link(LB); printf(""odd
""); print_link(LC);}追问:不需要整个程序,只要写一段实现要求的算法代码追答:那你只需要给出链表节点定义和 分离函数即可1.链表节点定义struct node{int data;struct node * next;};1.将链表分为奇数,偶数两个链表struct node ** devide_link(struct node * head){struct node *head_even_tmp = NULL;struct node *head_odd_tmp = NULL;struct node ** head_result = (struct node * *)malloc(2 * sizeof(struct node *));head_result[0] = NULL;head_result[1] = NULL;while (head){if (head->data % 2) //偶数{if (head_result[0] == NULL){head_result[0] = head;head_even_tmp = head;}else {head_even_tmp->next = head;head_even_tmp = head_even_tmp->next;}}else //奇数{if (head_result[1] == NULL){head_result[1] = head;head_odd_tmp = head;}else {head_odd_tmp->next = head;head_odd_tmp = head_odd_tmp->next;}}head = head->next;}if(head_odd_tmp)head_odd_tmp->next = NULL;if(head_even_tmp)head_even_tmp->next = NULL;return head_result;}追问:好的,谢谢啦
时间: 2024-11-02 21:55:52