今天开始来讲一下java中的数据结构之~单链表,数据结构就是数据在内存中存储的结
构,而单链表就是最简单的数据结果之一。今后我们学到的栈,队列都是需要在它的
上拓展。
先简单介绍一下单链表的一个基本类型我们称之为字节,一般字节中存储两类东西,
一种是需要携带的数据,另一种是下一个字节的地址。如图
上一个字节存储下一个字节的地址,而下一个有储存下下一个,继而形成一条链表,
方向只能从上一个指向下一个,单向指向,所以单链表就是这个由来。
需要注意的是两个字节的地址在内存中并没有什么联系,我们称之为逻辑上连续,物
理上无关。
那么单链表在java中在代码中到底是如何实现的?来看
class TestLink{
private Entry head;
public TestLink(){
head = new Entry();
}
class Entry{
int data;
Entry next;
public Entry(){
data = -1;
next = null;
}
public Entry(int val){
data = val;
next = null;
}
}
}
这里我们要用内部类来定义字节(Entry),在外部类中定义一个head类型的字节来
当头字节,在单链表中找到头,就可以找单链表中任何一个字节。
定义了单链表后我们来定义单链表中的方法(写在外部类中):
(1)头插节点(把新节点插在head后面)
public void insertHead(int val){
entry en = new entry(val);
en.next = head.next;
head.next = en;
}
(2)尾插法(新节点插到最后面)
public void inserttail(int val){
entry en = new entry(val);
entry cur = new entry();
cur = head;
while(cur.next!=null){
cur = cur.next;
}
cur.next = en;
}
(3)获取单链表的长度
public int getlenth(){
entry cur = head.next;
int len = 0;
while(cur!=null){
cur = cur.next;
len++;
}
return len;
}
(4)逆置单链表(不改变节点位置,只改变指向)
public entry reverse(){
entry newHead = null;
entry prev = null;
entry cur = head;
while(cur!=null){
entry curNext = cur.next;
if(curNext == null){
newHead = cur;
}
cur.next = prev;
prev = cur;
cur = curNext;
}
head = newHead;
return head;
}
(5)打印单链表(输出单链表的data)
public void show(){
entry cur = head.next;
while(cur!=null){
System.out.println("data: "+cur.data);
cur = cur.next;
}
}
(6)判断是否有环
public boolean isloop(){
entry fast = head;
entry slow = head;
while(fast !=null && fast.next !=null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
return true;
}
}
return false;
}
(7)获取环的长度
public int getEntrylenth(){
int len = 0;
entry fast = head;
entry slow = head;
boolean tag =false;
while(fast == slow&& tag==true){
fast = fast.next.next;
slow = slow.next;
if(fast ==slow&&tag == true){
break;
}
if(fast == slow&& tag==false){
tag = true;
}
if(tag ==true){
len++;
}
}
return len;
}
(8)判断两链表是否相交
public boolean isCut(testlink t1,testlink t2){
testlink.entry head1 = t1.head;
testlink.entry head2 = t2.head;
int len1 = t1.getlenth();
int len2 = t1.getlenth();
int my_len = len1-len2;
if(my_len < 0){
head1 = t2.head;
head2 = t1.head;
}
for(int i = 0;i<my_len;i++){
head1 = head1.next;
}
while(head1!=null&&head2 !=null&&head1!=head2){
head1 =head1.next;
head2 = head2.next;
}
if(head1 == head2&&head1!=null&&head2!=null){
return true;
}else{
return false;
}
}