简易的数组&链表生成器(2)

上一篇我们已经讲了数组生成框架和使用方法举例。这一篇我们讲一下链表的生成框架。数组和链表的生成框架是一脉相承的,我只需要继承原有的框架,做轻微修改就可以使用了。下面是单向链表的框架代码。可以跟数组的框架做一下比较,看看做了哪些改动。

单向链表的框架

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct node {
    struct node *next;
    int val;
}Node;


/* Put your function here */

int main(int argc, char *argv[])
{
    int i;
    unsigned int len;
    Node *vector = NULL;

    /* get the array lenth from input */
    scanf("%u", &len);

    vector = (Node *)malloc(len * sizeof(Node));
    if (NULL == vector) {
        return 1;
    }
    /* get the array value from input  */
    for (i=0; i<len; i++) {
        scanf("%d", &vector[i].val);
        if (i == len-1) {
            vector[i].next = NULL;
        } else {
            vector[i].next = &vector[i+1];
        }
    }

    /* function call */

    free(vector);
    return 0;
}

双向链表的框架

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct node {
    struct node *prev, *next;
    int val;
}Node;

/* Put your function here */

int main(int argc, char *argv[])
{
    int i;
    unsigned int len;
    Node *vector = NULL;

    /* get the array lenth from input */
    scanf("%u", &len);

    vector = (Node *)malloc(len * sizeof(Node));
    if (NULL == vector) {
        return 1;
    }
    /* get the array value from input  */
    for (i=0; i<len; i++) {
        scanf("%d", &vector[i].val);
        if (i == 0) {
            vector[i].prev = NULL;
            vector[i].next = &vector[i+1];
        } else if (i == len-1) {
            vector[i].prev = &vector[i-1];
            vector[i].next = NULL;
        } else {
            vector[i].prev = &vector[i-1];
            vector[i].next = &vector[i+1];
        }
    }

    /* function call */

    free(vector);
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浮沉飘摇

码字不易,打赏随意。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值