1.链表节点类
public class NodeLink {
public Object data;
public NodeLink next;
public NodeLink(Object data){
this.data=data;
} }
2.链表功能测试类
public class MyNode {
private static NodeLink head;
public static void main(String[] args) {
// TODO Auto-generated method stub
addNodeItem("aaa");//添加三个节点
addNodeItem("bbb");
addNodeItem("ccc");
addIndex(1,"wang");//添加指定的节点
deleteNode(1);//删除指定位置的节点
putNode(); //遍历输出节点
System.out.println("链表长度为:"+length()); //输出节点长度
checkNode("bbb");//查找节点bbb值 所在位置
}
//添加指定位置的节点
private static void addIndex(int index,Object value){
if(index<1||index>length()+1)
return ;
NodeLink temp=head;
NodeLink addNode=new NodeLink(value);
int len=1;
while(temp!=null){
if(index==len){
addNode.next=temp.next;
temp.next=addNode;
return ;
}
len++;
temp=temp.next;
}
}
//删除指定位置的节点
private static void deleteNode(int index){
if(index<1||index>length()+1)
return ;
NodeLink temp=head;
int len=1;
while(temp!=null){
if(index==len){
temp.next=temp.next.next;
return;
}
len++;
temp=temp.next;
}
}
//向尾节点添加新节点
private static void addNodeItem(Object value){
NodeLink addNode=new NodeLink(value);
if(head==null){
head=new NodeLink(value);
return;
}
//下面这句话很重要 temp和head的哈希码值相同 指向同一内存空间 所以temp新增的节点也链在head上
NodeLink temp=head;
while(temp.next!=null){
temp=temp.next;
}
temp.next=addNode;
}
private static int length(){
int len=0;
NodeLink temp=head;
while(temp!=null){
len++;
temp=temp.next;
}
return len;
}
//遍历节点
private static void putNode(){
NodeLink temp=head;
while(temp!=null){
System.out.println(temp.data);
temp=temp.next;
}
}
private static void checkNode(Object value){
NodeLink temp=head;
for(int i=0;i<length();i++){
if(temp.data.equals(value)){
System.out.println(temp.data+"位置在i="+(i+1));
break;
}
temp=temp.next;
}
//链表翻转
private static NodeLink reverseNodeTemp(NodeLink heads){
if(heads==null) return heads;
NodeLink per=null;
NodeLink temp;
while(heads!=null){
temp=heads.next;
heads.next=per;
per=heads;
heads=temp;
}
return per;
}
//递归翻转
//递归 翻转链表
private static NodeLink reverseNode(NodeLink heads){
if(heads.next==null) return heads;
NodeLink temp=
reverseNode(heads.next);
heads.next.next=heads;
heads.next=null;
return temp;
}
输出结果:
aaa
bbb
ccc
链表长度为:3
bbb位置在i=2
网友评论