【发布时间】:2014-05-07 09:52:40
【问题描述】:
我有Link1 class来创建链接并显示链接数据,
LinkedList1 创建列表并在LinkedList 中插入元素。singleLinkedList 类调用addFirst 和addLast. 的方法
实现细节如下。唯一的问题是在addlast方法的最后一个元素插入数据后,应该为最后一个链接设置的指针。
Link1 类实现
class Link1{
public String str;
public Link1 forward;
public Link1(String str){
this.str=str;
this.forward=null;
}
public void displayLink1(){
System.out.println("Link DATA::"+str);
}
}
LinkList1 类实现
class LinkedList1{
public Link1 first;
public LinkedList1(){
first=null;
}
public boolean isEmplty(){
return first==null;
}
public void addFirst(String str){
Link1 newLink=new Link1(str);
newLink.forward=first;
first=newLink;
}
public Link1 deleteFirst(){
Link1 temp=first;
first=first.forward;
return temp;
}
public void insertLast(String str){
Link1 current=first;
Link1 last=first;
Link1 newLinkLast=new Link1(str);
while(current!=null){
current=current.forward;
if(current==null);
{
last=current.forward; //trying to reach to end of the linkedlist
break;
}
}
newLinkLast.forward=last; //the last.displayLink is having the correct data evertime this is method getting called.But this is not going to my LinkedList
//COMMENTED****last.forward=newLinkLast //SOMETHING IS MESSED HERE,if i add one works perfect but the whole list gets messed up,including the elements added by insertFirst
last=newLinkLast;
last.displayLink1(); //Just for testing i am printing the value of this link,which is coming correct everytime i call this method.
}
public void displayOB(){
Link1 current=first;
while(current!=null){
current.displayLink1();
current=current.forward;
}
}
}
singleLinkedList 实现
公共类 singleLinkedList {
public static void main(String args[]){
LinkedList1 ll=new LinkedList1();
ll.addFirst("A");
ll.addFirst("B");
ll.addFirst("C");
ll.addFirst("d");
ll.addFirst("e");
ll.addFirst("f");
ll.addFirst("x");
ll.addFirst("y");
ll.addFirst("z");
ll.insertLast("Insert me at End 1");
ll.insertLast("Insert me at End 2");
ll.insertLast("Insert Again");
ll.displayOB();
}
}
输出 第一行是 newLinkLast.forward=last
Link DATA::Insert me at End 1 //this is the displayLink method called in insertLast
Link DATA::Insert me at End 2 //this is the displayLink method called in insertLast
Link DATA::Insert Again //this is the displayLink method called in insertLast
Link DATA::z
Link DATA::y
Link DATA::x
Link DATA::f
Link DATA::e
Link DATA::d
Link DATA::C
Link DATA::B
Link DATA::A
对于第二个 COMMENTED LINE 行,即 newLinkLast.forward=last
Link DATA::Insert me at End 1 //this is the displayLink method called in insertLast
Link DATA::Insert me at End 2 //this is the displayLink method called in insertLast
Link DATA::Insert Again //this is the displayLink method called in insertLast
Link DATA::z
Link DATA::y
Link DATA::x
Link DATA::Insert Again
预期结果 最后插入应该在最后插入元素任意次数。
【问题讨论】:
-
任何帮助!!!问题没有正确发布吗?信息不足。请告诉我。我希望解决这个问题。
标签: java algorithm data-structures linked-list