习题11-7 奇数值结点链表 (20分)
本题要求实现两个函数,分别将读入的数据存储为单链表、将链表中奇数值的结点重新组成一个新的链表。
- 核心
- 单链表的建立
struct ListNode *readlist()
{
struct ListNode *head, *tail, *p;
int n;
head = NULL;
tail = head;
while(n != -1)
{
scanf("%d", &n);
if (n != -1)
{
p = (struct ListNode*)malloc(sizeof(struct ListNode)); // 申请新节点
p -> data = n;
p -> next = NULL;
if (head == NULL) head = p; // 若为头节点时
else tail -> next = p;
tail = p;
}
}
return head;
}
- 奇数偶数分离
struct ListNode *getodd( struct ListNode **L )
{
struct ListNode *p, *p1, *p2, *h1 = NULL, *h2 = NULL;
int a;
while(*L)
{
a = (*L) -> data;
p = (struct ListNode*)malloc(sizeof(struct ListNode));
p -> data = a;
p -> next = NULL;
if (a % 2 == 1)
{
if (h1 == NULL) h1 = p;
else p1 -> next = p;
p1 = p;
}
else
{
if (h2 == NULL) h2 = p;
else p2 -> next = p;
p2 = p;
}
(*L) = (*L) -> next;
}
*L = h2;
return h1;
}
- code
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int data;
struct ListNode *next;
};
// 单链表的建立
struct ListNode *readlist()
{
struct ListNode *head, *tail, *p;
int n;
head = NULL;
tail = head;
while(n != -1)
{
scanf("%d", &n);
if (n != -1)
{
p = (struct ListNode*)malloc(sizeof(struct ListNode)); // 申请新节点
p -> data = n;
p -> next = NULL;
if (head == NULL) head = p; // 若为头节点时
else tail -> next = p;
tail = p;
}
}
return head;
}
struct ListNode *getodd( struct ListNode **L )
{
struct ListNode *p, *p1, *p2, *h1 = NULL, *h2 = NULL;
int a;
while(*L)
{
a = (*L) -> data;
p = (struct ListNode*)malloc(sizeof(struct ListNode));
p -> data = a;
p -> next = NULL;
if (a % 2 == 1)
{
if (h1 == NULL) h1 = p;
else p1 -> next = p;
p1 = p;
}
else
{
if (h2 == NULL) h2 = p;
else p2 -> next = p;
p2 = p;
}
(*L) = (*L) -> next;
}
*L = h2;
return h1;
}
void printlist( struct ListNode *L )
{
struct ListNode *p = L;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main()
{
struct ListNode *L, *Odd;
L = readlist();
Odd = getodd(&L);
printlist(Odd);
printlist(L);
return 0;
}
/* 你的代码将被嵌在这里 */
作者:stdxiaozhang
出处:https://www.cnblogs.com/stdxiaozhang/p/13389503.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
吼吼,如果对你有帮助的话,可以点个赞呀!
U Can Buy me a cup of 蜜雪冰城 ☕.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~