62,614
社区成员
发帖
与我相关
我的任务
分享
class Link{
public long dData;
public Link next;
public Link(long dd){
dData=dd;
}
//、、、、、、、、、、、、、、、
public void insert(long key){
Link newLink=new Link(key);
Link previous=null;
Link current =first;//这
if(previous==null)
first=newLink;//这
else
previous.next=newLink;
newLink.next=current;//这一点不明白什么意思,此时current的值是什么?null么?还有这句代码的意思
//是将指针指向本身么?(上面做标记的代码使我的理解是:newLink.next=newLink,但是我感觉不对啊)
}
Link newLink=new Link(key);//新的结点
Link current =first;//取出current结点
if(previous==null)//没有前置结点
first=newLink;//把新结点放入link的第一个位置
else//有前置结点
previous.next=newLink;//把前置结点的下一个结点引用指向新的结点
newLink.next=current;把新结点的下一个结点引用指向上面获取的current结点
package com.study.pratice03;
class Link
{
private Node root;
class Node
{
private Node next;
private String name;
public Node(String str)
{
this.name = str;
}
public String getName()
{
return this.name;
}
public void addNode(Node node)
{
if (this.next == null)
{
this.next = node;
}
else
{
this.next.addNode(node);
}
}
public void printNode()
{
if (this.next == null)
{
System.out.print(this.getName());
}
else
{
System.out.print(this.getName() + "->");
this.next.printNode();
}
}
public boolean searchNode(String name)
{
if (this.getName().equals(name))
{
return true;
}
else
{
if (this.next == null)
{
return false;
}
else
{
return this.next.searchNode(name);
}
}
}
public void deleteNode(Node preNode, String name)
{
if (this.getName().equals(name))
{
preNode.next = this.next;
}
else
{
this.next.deleteNode(this, name);
}
}
}
public void add(String name)
{
Node newNode = new Node(name);
if (root == null)
{
this.root = newNode;
}
else
{
this.root.addNode(newNode);
}
}
public void printLink()
{
if (root != null)
{
this.root.printNode();
}
}
public boolean search(String name)
{
if (this.root.getName().equals(name))
{
return true;
}
else
{
return this.root.next.searchNode(name);
}
}
public void delete(String name)
{
if (this.search(name))// 判断节点是否存在
{
if (this.root.getName().equals(name))// 判断要删除的节点是否是头结点
{
if (this.root.next == null)// 判断头节点是否有后续节点
{
this.root = null;
}
else
{
this.root = root.next;// 更改头结点
}
}
else
{
this.root.next.deleteNode(root, name);
}
}
else
{
System.out.println("要删除的节点不存在!");
}
}
}
public class LinkedNode
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Link l = new Link();
l.add("根节点");
l.add("第一个节点");
l.add("第二个节点");
l.add("第三个节点");
l.add("第四个节点");
l.add("第五个节点\n");
l.printLink();
System.out.println(l.search("根节点"));
l.delete("根节点");
l.printLink();
l.delete("第八个节点");
l.delete("第四个节点");
l.printLink();
}
}