关于用Java实现链表的问题

aleyn 2010-10-13 10:32:51



package SortInterface;

public class LinkList {//implements SortInterface{
private Node head;
private int length;

public LinkList(){
head=null;
length=0;
}
public void clearLinkList(){ //清空链表
head=null;
length=0;
}
public boolean isEmpty(){ //判断链表是否为空
return (length==0);
}
public void insert(int data) {
Node e = new Node(data);
if (length == 0) {
head=e;
}else {
e.next=head;
head=e;
}
length++;
}
////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
public boolean rmove(int data){
Node p=this.head,q=p;
if(length==0){
return false;
}
while(p!=null&&p.next.data!=data){
p=p.next;
}
if(p!=null){
q=p.next;
// p=q.next;
// q=null; //怎样删除结点q???? //怎样删除结点值为data的q结点????
length--; //
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
public void printLinkList(){
Node p=head;
while(p!=null){
System.out.print(" "+p.data);
p=p.next;
}
}
}

package SortInterface;

/**
*
* @author Administrator
*/
public class Node {
public int data;
public Node next;
public Node(){

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

问题是关于//////////////标注
处的函数怎样删除一个结点的问题 就是怎样删除结点q



package SortInterface;

/**
*
* @author Administrator
*/
public class TestList {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
LinkList link;
link=new LinkList();
link.insert(2);
link.insert(7);
link.insert(1);
link.insert(5);
link.insert(4);
link.printLinkList();
link.rmove(5);
System.out.println("\n删除元素后:");
link.printLinkList();
}

}
...全文
102 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
liufeng0209 2010-10-14
  • 打赏
  • 举报
回复
java API里有LinkedList 不明白你为什么要自己实现,有问题直接看源码吧
aleyn 2010-10-14
  • 打赏
  • 举报
回复
二楼的没有回答到问题的所在
ChDw 2010-10-13
  • 打赏
  • 举报
回复
首先while(p!=null&&p.next.data!=data)
应该增加p.next判断吧!


删除代码那里是 p.next = p.next.next;这样就跳过了包含data的那个Node了。
kebin0001 2010-10-13
  • 打赏
  • 举报
回复
改成回傳刪掉的個數。

public int rmove(int data) {
Node p = this.head;
Node q = this.head;
if (length == 0) {
return 0;
}
int removeCount=0;
while(this.head.data==data){
this.head = this.head.next;
p = this.head;
q = this.head;
this.length--;
removeCount++;
}
p=p.next;
while (p != null){
if(p.data==data){
p=p.next;
q.next=p;
this.length--;
removeCount++;
}else{
p = p.next;
q=q.next;
}
}
return removeCount;
}

67,512

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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