写双端链表简直是写双向链表的基础,重点是插入和删除操作时对first以及last结点的修改。其他的就没啥了吧。
package linkList;
/*
* 结点定义
*/
class Node{
Object data;
Node next;
public Node(Object d) {
this.data = d;
this.next = null;
}
public void display() {
System.out.print(data + " ");
}
}
/*
* 写一个双端链表
*/
public class firstlastList {
Node first;
Node last;
/*
* 构造器
*/
public firstlastList() {
this.first = null;
this.last = null;
}
/*
* 从头插入
*/
public void insertFirst(Object data) {
Node newNode = new Node(data);
if (isEmpty()) {
last = newNode;
}
newNode.next = first;
first = newNode;
}
/*
* 从尾部插入
*/
//无论怎样都要把newNode赋值给first和last
public void insertLast(Object data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
}else {
last.next = newNode;
}
last = newNode;
}
/*
* 任意位置插入结点
*/
public void insertLoc(int loc, Object d) {
Node current = first;
int j = 1;
Node newNode = new Node(d);
if(loc<1 || loc > length()+1) {
System.out.println("The location is not exit!");
return;
}
if(loc == j) {
newNode.next = current;
first = newNode;
return;
}
//定位到location-1的位置了
while(j<loc-1 & current!=null) {
current = current.next;
j++;
}
if(current == last) {
last = newNode;
}
newNode.next =current.next;
current.next = newNode;
System.out.println("last "+ last.data);
}
/*
* 一定要记得对last的处理
* (1) 当删除的结点只有一个结点时,记得要对last置空,而first
* 执行了first = first.next会自动置空
* (2) 当不只有一个结点时,遍历到location-1位置的结点,需要先
* 令last = current,再进行删除操作
* 对首结点删除也需要注意
* (1) 对首结点删除只需要执行first = first.next操作就可以,而
* 不必再执行current.next = current.next.next //将删除的前一个结点指向删除的下一个结点
*/
public void delete(int loc) {
Node current = first;
int j = 1;
System.out.println("开始的last:"+last.data);
if(loc<1 || loc>length()) {
System.out.println("The location to delete is not exit!");
return;
}
if(loc == j) {
if(first == last) {
last = null;
}
first = current.next;
return;
}
//遍历到current为第location-1的位置
while(j<loc-1) {
current = current.next;
j++;
}
if(current.next == last) {
last = current;
}
current.next = current.next.next;
System.out.println("first:" + first);
System.out.println("删除后的last:"+last);
}
/*
* 判断是否为空
*/
public boolean isEmpty() {
return(first == null);
}
public int length() {
int length = 0;
Node current = first;
while(current != null) {
length++;
current = current.next;
}
return length;
}
public void displayList() {
Node temp = first;
while(temp != null) {
temp.display();
temp = temp.next;
}
System.out.println();
}
//main
public static void main(String[] args) {
firstlastList list = new firstlastList();
list.insertFirst(22);
list.displayList();
list.insertLoc(3, 3);
list.displayList();
}
}