浅谈PHP链表数据结构(单链表)
链表:是一个有序的列表,但是它在内存中是分散存储的,使用链表可以解决类似约瑟夫问题,排序问题,搜索问题,广义表
单向链表,双向链表,环形链表
PHP的底层是C,当一个程序运行时,内存分成五个区(堆区,栈区,全局区,常量区,代码区)
规定:基本数据类型,一般放在栈区
复合数据类型,比如对象,放在堆区
定义一个类Hero
定义成员属性排名$no
定义成员属性姓名$name
定义成员属性昵称$nickname
定义成员属性$next,是一个引用,指向下一个Hero对象
定义构造函数,传递参数:$no,$name,$nickname
创建一个头head,该head只是一个头,不放入数据
获取$head对象,newHero()
获取第一个Hero对象$hero,newHero(1,”宋江”,”及时雨”)
连接两个对象,$head->next=$hero
获取第二个Hero对象$hero2,newHero(2,”卢俊义”,”玉麒麟”)
连接两个对象,$hero->next=$hero2
遍历链表
定义一个函数showHeros(),参数:$head对象
定义一个临时变量$cur来存储$head对象
while循环,条件$cur->next不为null
打印一下
指针后移,$cur=$cur->next
PHP版:
<?php
/**
*英雄类
*/
classHero{
public$no;
public$name;
public$nickname;
public$next=null;
publicfunction__construct($no='',$name='',$nickname=''){
$this->no=$no;
$this->name=$name;
$this->nickname=$nickname;
}
}
classLinkListDemo{
publicstaticfunctionmain(){
$head=newHero();
$hero1=newHero(1,"宋江","及时雨");
$head->next=$hero1;
$hero2=newHero(2,"卢俊义","玉麒麟");
$hero1->next=$hero2;
LinkListDemo::showHeros($head);
}
/**
*展示英雄
*/
publicstaticfunctionshowHeros($head){
$cur=$head;
while($cur->next!=null){
echo"姓名:".$cur->next->name."<br/>";
$cur=$cur->next;
}
}
}
LinkListDemo::main();
java版:
classHero{
publicintno;
publicStringname;
publicStringnickname;
publicHeronext=null;
publicHero(){
}
publicHero(intno,Stringname,Stringnickname){
this.no=no;
this.name=name;
this.nickname=nickname;
}
}
publicclassLinkListDemo{
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
Herohead=newHero();
Herohero1=newHero(1,"宋江","及时雨");
head.next=hero1;
Herohero2=newHero(2,"卢俊义","玉麒麟");
hero1.next=hero2;
showHeros(head);
}
/**
*展示英雄
*@paramhead
*/
publicstaticvoidshowHeros(Herohead){
Herocur=head;
while(cur.next!=null){
System.out.println("姓名:"+cur.next.name);
cur=cur.next;
}
}
}
以上这篇浅谈PHP链表数据结构(单链表)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。