简易的数组&链表生成器(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;
}



发布了27 篇原创文章 · 获赞 2 · 访问量 4627

猜你喜欢

转载自blog.csdn.net/xqjcool/article/details/48338449
今日推荐