简单的单链表的程序补全,delete(int value)方法怎么写呢?

ladofwind 2003-08-12 10:53:32
public class Node{

private int data; //数据域,记录节点中保存的数据
private Node next; //节点中的指针域属性,指向后继节点对象
public static void main(String[] args){
Node a=new Node(1);
Node b=new Node(2);
Node c=new Node(3);
Node d=new Node(4);
Node e=new Node(5);
Node f=new Node(6);
a.setNext(b);
b.setNext(c);
c.setNext(d);
d.setNext(e);
e.setNext(f);
a.printNode();
a.delete(3);
a.printNode();

}
public void printNode(){
Node tem=this;
while(tem!=null){
System.out.println(tem.data);
tem=tem.next;
}
}
public Node(int data){
this.data = data;
next = null;
}

public Node(int data,Node next){
this.data = data;
this.next = next;
}

public void setData(int data){
this.data = data;
}

public int getData(){
return data;
}

public void setNext(Node next){
this.next = next;
}

public Node getNext(){
return next;
}
public Node delete(int value){
//删除链表中data为value的元素,
         返回链表头节点!
}

}
...全文
15 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
litfool 2003-08-12
  • 打赏
  • 举报
回复
1、需要在类中设置一个变量时刻记录头节点,如Node header;

2、Node nReturn=header;
if(header!=null)
{
if(header.getData()==value)
{
nReturn=header.next();
header=null;
return nReturn;
}
else
{
Node preNode=header;
Node nowNode=header.next();
while(nowNode!=null)
{
if(nowNode.getValue()==value)
{
preNode.setNext(nowNode.getNext());
nowNode==null;
return nReturn;
}
else
{
preNode=nowNode;
nowNode=nowNode.getNext();
}
}
}
}
return nReturn;
yoken 2003-08-12
  • 打赏
  • 举报
回复
你的这种class无法得到头节点的reference,因而无法遍历整个链表,从而delete(int value)无法实现,这种class的思路是仿照c里的实现方法,不太像面向对象的思想
java里好像无需链表,有许多好用的container

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧