面试宝典中第13章,实现单链表的建立测长和打印
#include<iostream>
#include <stdio.h>
#include <string.h>
#include<conio.h>
using namespace std;
//单链表结构体
typedef struct student
{
int data;
struct student *next;
}node;
//建立单链表
node *create()
{
node *head,*p,*s;
int x,cycle=1;
head=(node*)malloc(sizeof(node)); //建立头节点
p=head;
while(cycle)
{
cout<<"Please input the data:"<<endl;
cin>>x;
if(x!=0)
{
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",head->data);
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",n);
p=head;
if(head!=NULL)
p=p->next;
while(p!=NULL)
{
printf("\n uuu %d ",p->data);
p=p->next;
}
}
void main()
{
//typedef struct Node *LinkList;
create();
}
备注:
6 | typedef struct Node *LinkList; |
关于C语言的struct
typedef为C语言的关键字,作用是为一种数据类型定义一个新名字。这里的数据类型包括内部数据类型(int,char等)和自定义的数据类型(struct等)。
在编程中使用typedef目的一般有两个,一个是给变量一个易记且意义明确的新名字,另一个是简化一些比较复杂的类型声明。