程序员面试宝典之数据结构基础----①单链表的建立、测长、打印(读后)

单链表的逆序(递归非递归),删除节点,插入,排序都很熟悉了,如果面试遇到,相信大家都能够写出来,但是,今天看到这个题目的时候,却花了一些时间来捉摸,不是难,二十有很多细节要注意:下面是程序员面试宝典书三上的代码,稍稍有点改动。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//notice the define of struct, the node is not a variable,it is the name of the struct.so it can be used to define the struct variable.
//notice the key word of typedef. if there is not the key word ,the node will have different properties.
typedef struct student
{
    int data;
    struct student* next;
}node;
node* creat()
{
    node* head,*p,*s;
    int x=0,cycle = 1 ;
    head=(node*)malloc(sizeof(node));   //notice the malloc is contained in the lib of <stdlib.h> and must malloc the space for the node before you use it.
    p = head;
    while(cycle)
    {
        printf("\nPlease input the data:");
        scanf("%d",&x);
        if(x!= 0)   // only for test ,so the '0' is the symblo of the end but the value of the node,I ignore this kind of possible. Of course you can do it .
        {
            s = (node*)malloc(sizeof(node));
            s->data = x;
            printf("\n%d",s->data);
            p->next = s;
            p = s;
        }
        else
        cycle = 0;

    }
    head = head->next;
    p->next = NULL;

    printf("\n  yyy  %d %d %d %d",head->data,head->next->data,head->next->next->data, head->next->next->next->data);//print four node for test.
    return(head);
}
int length(node* head)
{
    int n = 0;
    node *p;
    p = head;
    while(p!=NULL)
    {
        p = p->next;
        n++;

    }
    return n;
}
void print(node* head)
{
    node *p;
    int n;
    n = length(head);
    printf("\nNow,These %d records are:",n);
    p = head;
    if(head!= NULL)
    {
        while(p != NULL)
        {
        printf("\n   uuu  %d   ",p->data);
        p = p->next;
        }
    }
    }
int main()
{
    node* head = creat();
    print(head);
}

 输出结果: 



Please input the data:1


1
Please input the data:2


2
Please input the data:3


3
Please input the data:4


4
Please input the data:5


5
Please input the data:6


6
Please input the data:7


7
Please input the data:0


  yyy  1 2 3 4
Now,These 7 records are:
   uuu  1
   uuu  2
   uuu  3
   uuu  4
   uuu  5
   uuu  6
   uuu  7
Process returned 0 (0x0)   execution time : 6.685 s
Press any key to continue.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值