关于链表的拆分
拆分技术主要用于将一个链表分开,或者是按照一定的规律排列完再合并为一条链表。
下面是最简单的一种a,b成对出现
#include <stdio.h> #include <stdlib.h> typedef struct Node{ int content; struct Node* next; }LNode; init(LNode** head){ *head = (LNode*)malloc(sizeof(LNode)); (*head)->content = 0; (*head)->next = NULL; } insert(LNode* head, int num){ LNode* newNode = (LNode*)malloc(sizeof(LNode)); newNode->content = num; newNode->next = head->next; head->next = newNode; } printL(LNode* head){ head = head->next; while (head != NULL){ printf("%d ", head->content); head = head->next; } } chaiFen(LNode *head, LNode** ha, LNode** hb){ LNode *ta, *tb; LNode *p, *q; p = head->next; q = p->next; *ha = (LNode*)malloc(sizeof(LNode)); *hb = (LNode*)malloc(sizeof(LNode)); ta = *ha; tb = *hb; while (1){ ta->next = p; ta = p; tb->next = q; tb = q; if (q->next == NULL) break; p = q->next; q = p->next; } p->next = NULL; q->next = NULL; } main(){ LNode* head; LNode* ha; LNode* hb; init(&head); insert(head, 0); insert(head, 1); insert(head, 2); insert(head, 3); insert(head, 4); insert(head, 5); insert(head, 6); insert(head, 7); insert(head, 8); insert(head, 9); printL(head); chaiFen(head, &ha, &hb); if (ha->next == NULL) printf("Error"); printL(ha); printL(hb); }
下面这种更优,适用于非成对出现:
#include <stdio.h> #include <stdlib.h> typedef struct Node{ int content; struct Node* next; }LNode; init(LNode** head){ *head = (LNode*)malloc(sizeof(LNode)); (*head)->content = 0; (*head)->next = NULL; } insert(LNode* head, int num){ LNode* newNode = (LNode*)malloc(sizeof(LNode)); newNode->content = num; newNode->next = head->next; head->next = newNode; } printL(LNode* head){ head = head->next; while (head != NULL){ printf("%d ", head->content); head = head->next; } } chaiFen(LNode *head, LNode** ha, LNode** hb){ int i = 0; LNode *ta, *tb; LNode *p; p = head->next; *ha = (LNode*)malloc(sizeof(LNode)); *hb = (LNode*)malloc(sizeof(LNode)); ta = *ha; tb = *hb; while (1){ if (i % 2 == 0){ ta->next = p; ta = p; } else{ tb->next = p; tb = p; } if (p->next == NULL) break; p = p->next; i++; } ta->next = NULL; tb->next = NULL; } main(){ LNode* head; LNode* ha; LNode* hb; init(&head); //insert(head, 0); insert(head, 1); insert(head, 2); insert(head, 3); insert(head, 4); insert(head, 5); insert(head, 6); insert(head, 7); insert(head, 8); insert(head, 9); printL(head); chaiFen(head, &ha, &hb); printL(ha); printL(hb); }