1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| #include <bits/stdc++.h> using namespace std; typedef struct Node { int elem; struct Node *next; }*Linklist; void inlinklist(Linklist &l, int n) { l = (Linklist)malloc(sizeof(Node)); l->next = NULL; Linklist p, END; END = l; printf("请输入想要创建的链表元素:\n"); for(int i = 0; i < n; i++) { p = (Linklist)malloc(sizeof(Node)); scanf("%d", &p->elem); END -> next = p; p->next = NULL; END = p; } } void outlinklist(Linklist l) { printf("链表中的值为:\n"); Linklist p; p = l->next; while(p != NULL) { printf("%d ", p->elem); p = p->next; } printf("\n"); } void splitlinklist(Linklist &l1, Linklist &l2, Linklist &l3) { l2 = (Linklist)malloc(sizeof(Linklist)); l3 = (Linklist)malloc(sizeof(Linklist)); Linklist p, q, s; p = l1; q = l2; s = l3; p = l1 -> next; q -> next = s -> next = NULL; while(p) { if(p->elem % 2 == 1) { q -> next = p; p = p -> next; q = q -> next; q -> next = NULL; } else if(p->elem % 2 == 0) { s -> next = p; p = p -> next; s = s -> next; s -> next = NULL; } } } int main(void) { ios::sync_with_stdio(false); cin.tie(0); Linklist L1, L2, L3; int n; printf("请输入创建n个元素的链表的n值:\n"); scanf("%d", &n); inlinklist(L1, n); splitlinklist(L1, L2, L3); outlinklist(L2); outlinklist(L3); return 0; }
|