Linux下学C语言——第十九节 数据结构

编程入门 行业动态 更新时间:2024-10-06 22:23:02

Linux下学C语言——第十九节 <a href=https://www.elefans.com/category/jswz/34/1769880.html style=数据结构"/>

Linux下学C语言——第十九节 数据结构

1.数学合并同类项算法:

#include <stdio.h>
#include <stdlib.h>typedef struct node_st
{int coef;int exp;struct node_st *next;
}node;node *poly_creat(int a[][2],int n)
{node *me;node *new,*cur;int i;me = malloc(sizeof(*me));if(me == NULL)return NULL;cur = me;for(i=0;i<n;i++){new = malloc(sizeof(*new));if(new == NULL)return NULL;new ->coef = a[i][0];new ->exp = a[i][1];new ->next = NULL;cur->next = new;cur = new;}return me;}
void poly_show(node *me)
{node *cur;for(cur = me ->next;cur != NULL;cur = cur ->next){printf("(%d,%d)",cur->coef,cur -> exp);}printf("\n");
}
void poly_union(node * p1,node *p2){node *p,*q;node *r;p = p1 ->next;q = p2 ->next;r = p1;while(p&&q){if(p->exp < q->exp){r -> next = p;r = p;p = p->next;}else if(p->exp > q ->exp){r->next = q;r =q;q = q->next;}else//p->exp == q->exp{p->coef += q->coef;if(p->coef){r->next =p;r = p;}p = p->next;q = q->next;}}}int main()
{int a[][2] = {{5,0},{2,1},{8,8},{3,16}};int b[][2] = {{6,1},{16,6},{-8,8}};node *p1, *p2;p1 = poly_creat(a,4);if(p1 == NULL)exit(1);p2 = poly_creat(b,3);if(p2 ==NULL)exit(1);poly_show(p1);poly_show(p2);poly_union(p1,p2);poly_show(p1);exit(0);
}

执行:

[tom@CentOS7 polynomial]$ ./poly 
(5,0)(2,1)(8,8)(3,16)
(6,1)(16,6)(-8,8)
(5,0)(8,1)(16,6)(-8,8)

2.报数出局小游戏

#include <stdio.h>
#include <stdlib.h>#define JOSE_NR 8typedef struct node_st
{int data;struct node_st *next;
}node;node *jose_creat(int n)
{node *me;node *new,*cur;int i = 1;me = malloc (sizeof(*me));if(me == NULL)return NULL;me ->data = i;me ->next = me;i++;cur = me;for(;i<= n;i++){new=malloc (sizeof(*new));if(new == NULL){return NULL;}printf("%d\n",i);new ->data = i;new -> next = me;cur -> next = new;cur = new;}return me;
}void jose_show(node *me)
{node *list;for(list = me;list -> next != me;list = list->next){printf("%d ",list ->data);}printf("%d\n",list->data);
}
void jose_kill(node **me,int n)
{node *cur =*me,*node;int i =1;while (cur != cur ->next){while(i<n){node = cur;cur = cur ->next ;i++;}printf("%d",cur ->data);node->next = cur ->next;free(cur);cur = node ->next;i= 1;}*me = cur;printf("\n");}
int main()
{   node *list;list = jose_creat(JOSE_NR);if(list == NULL)exit(1);jose_show(list);jose_kill(&list,3);jose_show(list);exit(0);
}

执行:隔三出局一个人,最后剩7号

1 2 3 4 5 6 7 8

7

更多推荐

Linux下学C语言——第十九节 数据结构

本文发布于:2024-02-28 02:14:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1767626.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据结构   语言   第十九节   Linux

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!