您的位置:首页 > 运维架构 > Linux

Linux下的C语言学习笔记(3)

2016-08-06 11:36 393 查看
------------------------------day12---动态数据结构-静态链表-动态链表---------------------------------------

1,静态链表:
#include<stdio.h>
struct weapon{
    int price;
    int atk;
    struct weapon * next;
};
int main(){
    struct weapon a,b,c,*head;
    a.price = 100;
    a.atk = 100;
    b.price = 200;
    b.atk = 200;
    c.price = 300;
    c.atk = 300;
    head = &a;
    a.next = &b;
    b.next = &c;
    c.next = &NULL;
    
    truct weapon * p;
    p = head;
    while(p!=NULL){
        printf("%d,%d",p->atk,p->price);
        p = p->next;
    }
    return 0;
}
2,动态链表:

#include<stdio.h>
#include<malloc.h>
struct weapon{
    int price;
    int atk;
    struct weapon * next;
};
struct weapon * creat(){
    struct weapon * head;
    struct weapon * p1,*p2;
    int n = 0;
    //malloc分配内存块的函数sizeof判断数据类型长度符
    p1=p2=(struct weapon *)malloc(sizeof(struct weapon));
    scanf("%d,%d",&p1->price,&p1->atk);
    head = NULL;
    while(p1->price!=0){
        n++;
        if(n==1) head=p1;
        else p2->next = p1;
        
        p2=p1;
        p1=(struct weapon *)malloc(sizeof(struct weapon));
        scanf("d,%d",&p1->price,&p1->atk);
    }
    p2->next=NULL;
    return (head);
}
int main(){
    struct weapon *p ;
    p=creat();
    printf("%d,%d\n",p->price,p->atk);
    return 0;
}

------------------------------day12---递归调用---------------------------------------

//函数自己调用自己
#include<stdio.h>
int func(int n){
    int r;
    if(n<0){
        printf("data error\n");
    }else if(n==0|| n==1){
        r=1;
    }else
    r = n*func(n-1);
    return r
}
int main(){
    int n;
    printf("please input n\n");
    scanf("%d",&n);
    int result = func(n);
    printf("result is :\n",result);
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息