奇数值结点链表
1 /* 2 QQ:7878138708 3 date:2020年5月16日 4 奇数值结点链表 5 */ 6 #include <stdio.h> 7 #include <stdlib.h> 8 9 struct ListNode { 10 int data; 11 struct ListNode *next; 12 }; 13 struct ListNode *readlist(void); 14 struct ListNode *getodd(struct ListNode **L); 15 void printlist(struct ListNode *L); 16 int main(void) 17 { 18 struct ListNode *L, *Odd; 19 L = readlist(); 20 21 Odd = getodd(&L); 22 printlist(Odd); 23 printlist(L); 24 25 return 0; 26 } 27 //新建一个链表 28 struct ListNode *readlist(void) 29 { 30 struct ListNode *head, *tail, *p; 31 int n; 32 head = tail = NULL; //表头、表尾都为空 33 scanf("%d", &n); 34 while (n != -1) { 35 //新建一个结点 36 p = (struct ListNode *)malloc(sizeof(struct ListNode)); 37 p->data = n; 38 p->next = NULL; 39 40 if (head == NULL) { 41 head = tail = p; 42 } 43 else 44 { 45 tail->next = p; 46 tail = p; 47 } 48 49 scanf("%d", &n); 50 } 51 52 return head; 53 } 54 void printlist(struct ListNode *L) 55 { 56 struct ListNode *p = L; 57 58 while (p != NULL) { 59 printf("%d ", p->data); 60 p = p->next; 61 } 62 63 printf("\n"); 64 } 65 struct ListNode *getodd(struct ListNode **L) 66 { 67 struct ListNode *oddHead, *oddTail; //奇数链表头尾 68 struct ListNode *evenHead, *evenTail; //偶数链表头尾 69 struct ListNode *p, *temp; 70 71 oddHead = oddTail = NULL; 72 evenHead = evenTail = NULL; 73 p = *L; 74 //遍历原来的链表 75 while (p) { 76 temp = p; 77 p = p->next; 78 //结点值为奇数 79 if (temp->data % 2) { 80 if (oddHead == NULL) { 81 oddHead = temp; 82 oddHead->next = NULL; 83 oddTail = oddHead; 84 } else { 85 oddTail->next = temp; 86 oddTail = oddTail->next; 87 oddTail->next = NULL; 88 } 89 } else { 90 if (evenHead == NULL) { 91 evenHead = temp; 92 evenHead->next = NULL; 93 evenTail = evenHead; 94 } else { 95 evenTail->next = temp; 96 evenTail = evenTail->next; 97 evenTail->next = NULL; 98 } 99 } 100 } 101 *L = evenHead; 102 103 return oddHead; 104 }