单链表的建立/测长/打印

单链表的创建过程有以下几步:

1 ) 定义链表的数据结构;

2 ) 创建一个空表;

3 ) 利用malloc ( )函数向系统申请分配一个节点;

4 ) 将新节点的指针成员赋值为空。若是空表,将新节点连接到表头;若是非空表,将新

节点接到表尾;

5 ) 判断一下是否有后续节点要接入链表,若有转到3 ),否则结束;

//
//  main.c
//  simple-list
//
//  Created by DOLFVE on 15-4-15.
//  Copyright (c) 2015年 DOLFVE. All rights reserved.
//

#include <stdio.h>
#include <stdlib.h>/*含malloc()的头文件*/

struct node
{
    int num;
    struct node *next;
};


int main() {
    struct node *create();
    void print();
    struct node *head;
    head = NULL;
    head = create(head);
    print(head);
}

struct node *crete(struct node *head)//返回的是与节点相同类型的指针
{
    struct node *p1, *p2;
    //①利用malloc()函数向系统申请分配一个节点
    p1 = p2 = (struct node*)malloc(sizeof(struct node));//新节点
//    printf("p1 = %d\n", p1);
    scanf("%d",&p1->num);//输入节点的值
    p1->next = NULL;//将新节点的指针置为空
    while (p1->num > 0)//输入的节点数值大于0
    {
        if (head == NULL) {
            head = p1;//如果是空表,就接入表头
        }
        else{
            p2->next = p1;//非空表,就接到表尾
        }

        p2 = p1;
        p1 = (struct node*)malloc(sizeof(struct node));
//        printf("p2 = %d\n", p2);
        scanf("%d", &p1->num);//输入节点的值
        //判断是否有后续节点要接入链表,若有,就接入①,否则结束
    }
//    printf("p2->next = %d\n", p2->next);
    return head;
}

void print (struct node *head)//输出以head为头的链表各节点的值
{
    struct node *temp;
    temp = head;//取得链表的头指针
    while (temp != NULL)//只要是非空表
    {
        printf("%6d", temp->num);//输出链表节点的值
        temp = temp->next;//跟踪链表增长
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值