微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C语言 翁凯老师 数据结构 链表学习1

链表的建立

linked-list.c

#include"node.h"
#include<stdio.h>
#include<stdlib.h>

// typedef struct _node
// {
//     int value;
//     struct  _node *next;
// } Node;

int main()
{
    Node * head = NULL;//初始化
    int number;
    do{
        scanf("%d",&number);
        if(number != 1){
            //add to linked-list
            Node *p = (Node*)malloc(sizeof(Node));
            p->value = number;
            p->next = NULL;
            //find the last
            Node *last = head;
            if(last){
                 while (last->next){//遍历到last->next=NULL为止,保证数据存储在链表的最后一位
                  last = last->next;
                }
                //attach
                last->next = p;
            }else{
                head = p;
            }
        }
    }while (number != -1);

    printf("%d",head->value);//为了验证链表的有效性
    
    return 0;
}

node.h

#ifndef _NODE_H_
#define _NODE_H_

typedef struct _node
{
    int value;
    struct  _node *next;
} Node;

#endif

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐