单链表的创建 测长和打印

来源:互联网 发布:上瘾网络剧下载种子 编辑:程序博客网 时间:2024/05/16 18:08

面试宝典中第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();}
备注:

1typedef struct Node

2{
3    ElemType data;
4    structNode *next;
5}Node;
6typedef struct Node *LinkList; /* 定义LinkList */
  • 从这个结构定义中,我们知道,结点由存放数据元素的数据域存放后继结点地址的指针域组成。
  • 假设p是指向线性表第i个元素的指针,则该结点ai的数据域我们可以用p->data来表示,p->data的值是一个数据元素,结点ai的指针域可以用 p->next来表示,p->next的值是一个指针。p->next指向谁呢?当然是指向第i+1个元素,即指向ai+1的指针。
  • 关于结构体 struct Node *next; 这么一句代码,为什么要这么写?我写成 int *next 行不行?
  • 不行的。next是指向下一个Node,所以其类型必须是Node。int *next 只能指向int,而不能指向Node。所以必须定义为 Node 类型,但是 Node 是结构体,所以前面还得加上个 struct。

关于C语言的struct

typedef为C语言的关键字,作用是为一种数据类型定义一个新名字。这里的数据类型包括内部数据类型(int,char等)和自定义的数据类型(struct等)。

在编程中使用typedef目的一般有两个,一个是给变量一个易记且意义明确的新名字,另一个是简化一些比较复杂的类型声明。


0 0