c语言链表

您所在的位置:网站首页 表链子怎么拆视频 c语言链表

c语言链表

2024-07-12 14:10| 来源: 网络整理| 查看: 265

首先我们看题目

输入N个整数顺序建立一个单链表,将该单链表拆分成两个子链表,第一个子链表存放了所有的偶数,第二个子链表存放了所有的奇数。两个子链表中数据的相对次序与原链表一致。

输入格式:

第一行输入整数N;; 第二行依次输入N个整数。

输出格式:

第一行分别输出偶数链表与奇数链表的元素个数; 第二行依次输出偶数子链表的所有数据; 第三行依次输出奇数子链表的所有数据。

输入样例: 10 1 3 22 8 15 999 9 44 6 1001 输出样例: 4 6 22 8 44 6 1 3 15 999 9 1001

代码长度限制

16 KB

时间限制

400 ms

内存限制

64 MB

栈限制

8192 KB

#include #include //先定义好节点结构体 typedef struct node { int data; struct node *next; }node; int cnt1, cnt2; //由于函数内的变量是局部变量所以我们选择放到全局,不管在哪里都可以使用 // 申请空间 node *arr_mal(struct node *p) { p = (struct node *)malloc(sizeof(struct node)); return p; } //一般只有头节点分配空间就可以了 //顺序建链表 void arr_create( node *head, int n) { node *p = NULL, *tail = NULL; tail = head;//顺序建链表首先头尾节点相同位置 while (n--) { p = arr_mal(p); scanf("%d", &p->data); tail->next = p; tail = tail->next; } } // 输出链表 void arr_prin(struct node *head) { struct node *p = NULL;//头节点是空的 p = head->next;//真正输出的实际值是从头节点之后的那个开始 //首先输出头节点 if (p != NULL) { printf("%d", p->data); p = p->next; } //输出头节点后的元素 while (p != NULL) { printf(" %d", p->data); p = p->next; } printf("\n"); } // 拆分 void arr_split(struct node *head1, struct node *head2) { struct node *p1 = NULL, *p2 = NULL, *tail = NULL; p1 = head1; p2 = head2; while (p1->next != NULL) { if (p1->next->data % 2) { p1 = p1->next; cnt1++; } else { tail = p1->next;//tail是第一个节点 p1->next = tail->next; tail->next = NULL; p2->next = tail; p2 = p2->next; cnt2++; } } } int main() { int n; cnt1 = cnt2 = 0; node *head1 = NULL, *head2 = NULL; head1 = arr_mal(head1);//分配空间 head2 = arr_mal(head2); scanf("%d", &n); arr_create(head1, n);//建链表 arr_split(head1, head2);//链表拆分 printf("%d %d\n", cnt2, cnt1); arr_prin(head2); arr_prin(head1); return 0; }



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3