c语言数据结构,求算法
论文问答
1
把一个单链表LA中的奇数项和偶数项分开,分别放在两个单链表LB,LC中(要求利用原空间,头结点空间可另外开辟)
-
//输入时以-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\n"); 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("\n"); } 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\n"); print_link(LB); printf("odd\n"); 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; } 追问: 好的,谢谢啦
发表回复