这里双端链表只是比传统链表多了一个对最后一个元素的引用——last
/*
*
*
*demonstrates list with first and last references
*
*/
class Link
{
public long dData;
public Link next;
public Link(long d)
{
dData = d;
}
public void displayLink()
{
System.out.print("{" + this.dData + "}");
}
}
class FirstLastList
{
private Link first;
private Link last;
public FirstLastList()
{
first = null;
last = null;
}
public boolean isEmpty()
{
return first == null;
}
public void insertFirst(long dd) //insert at front of list
{
Link newLink = new Link(dd);
if(this.isEmpty()) //***********somewhat different!
{
first = newLink;
last = newLink;
}
else
{
newLink.next = first;
first = newLink;
}
}
public void insertLast(long dd) //insert at end of list
{
Link newLink = new Link(dd);
if(this.isEmpty())
{
first = newLink; //***********somewhat different
last = newLink;
}
else
{
last.next = newLink;
newLink.next = null;
last = newLink;
}
}
public long deleteFirst()
{
/* by me , I didn't consider when just one element exists in list
Link current = null;
if(this.isEmpty())
{
System.out.println("your list is an empty one!");
return 0;
}
else
{
current = first;
first = first.next;
return current.dData;
}
*/
//by textbook
long temp = first.dData;
if(first.next == null)
{
last = null;
}
first = first.next;
return temp;
}
public void displayList() //display the list;
{
Link current = first;
if(this.isEmpty())
{
System.out.println("The current list is empty, please insert some elements!");
}
else
{
System.out.print("List(first-->last): ");
while(current!=null) //if I write like this: while(current.next!=null) ,I just miss last element in list
{
current.displayLink();
current = current.next;
}
System.out.println("");
}
}
}
public class FirstLastListApp
{
public static void main(String[] args)
{
FirstLastList list = new FirstLastList();
list.insertFirst(100); // insert at front
list.insertFirst(200);
list.insertFirst(600);
list.insertLast(514); //insert at rear
list.insertLast(564);
list.displayList(); //display the list
list.deleteFirst(); //delete two items(elements)
list.deleteFirst();
list.displayList(); //display again
}
}
运行效果: