仅用于学习记录 链表作为重要的数据结构,HashMap的底层结构都是链表结构,链表以结点作为存储单元,结点由存储的数值+指向后序结点的指针。
单链表结点
package shiyan1
;
public class Node<T>{
T data
;
Node
<T> next
;
public Node(){
this(null
, null
);
}
public Node(T data
,Node
<T> next
){
this.data
= data
;
this.next
= next
;
}
public String
toString(){
return this.data
.toString();
}
public static void main(String
[] args
) {
}
}
Node的用途 T作为泛型,定义Node中存储的数值的类型
链表的实现
package shiyan1
;
import shiyan1
.List
;
import shiyan1
.Node
;
interface List<T>{
void insert(int index
,T data
);
T
remove(int i
);
boolean isEmpty();
String
toString();
void reserveLink();
}
public class SinglyList <T> implements List<T>{
Node
<T> head
= null
;
public boolean isEmpty() {
return this.head
.next
==null
;
}
public T
get(int i
){
Node
<T> p
= this.head
.next
;
for(int j
=0;p
!=null
&& j
<i
;j
++)
p
=p
.next
;
return p
.data
;
}
public void insert(int index
, T data
) {
if(head
==null
){
head
= new Node<T>(data
,null
);
return;
}
Node
<T> front
= this.head
;
for(int j
=0;front
.next
!=null
&& j
<index
; j
++)
front
= front
.next
;
front
.next
= new Node<T>(data
,front
.next
);
}
public T
remove(int i
) {
Node
<T> front
= this.head
;
for(int j
=0;front
.next
!=null
&&j
<i
-1;j
++){
front
=front
.next
;
}
if(i
==0 && head
!=null
) {
head
= head
.next
;
}
if(i
>0 && front
.next
!=null
){
T x
= front
.next
.data
;
front
.next
= front
.next
.next
;
return x
;
}
return null
;
}
public void printLink(){
Node
<T> curNode
= head
;
while(curNode
!=null
){
System
.out
.print(curNode
.data
+" ");
curNode
= curNode
.next
;
}
System
.out
.println();
}
public void reserveLink(){
Node
<T> curNode
= head
;
Node
<T> preNode
= null
;
while(curNode
!= null
){
Node
<T> nextNode
= curNode
.next
;
curNode
.next
= preNode
;
preNode
= curNode
;
curNode
= nextNode
;
}
head
= preNode
;
}
}
测试类
package shiyan1
;
public class text {
public static void main(String
[] args
) {
SinglyList
<String> list
= new SinglyList<String>();
list
.insert(0, "A");
list
.insert(1, "B");
list
.printLink();
list
.reserveLink();
list
.printLink();
}
}