public class implements_linklist{
public static void main(String [] args)
{
Bi_directLinklist<String> bi_directLinklist = new Bi_directLinklist<String>();
bi_directLinklist.pre_add("this is first node");
bi_directLinklist.pre_add("this is 2th node");
bi_directLinklist.pre_add("this is 3th node");
bi_directLinklist.pre_add("this is 4th node");
bi_directLinklist.pre_add("this is 5th node");
bi_directLinklist.ergodic();
}
}
//双向链表(模板类)带头尾节点的链表
class Bi_directLinklist<T>{
private static class Node<T>{
//定义前后指针
Node<T> pre;
Node<T> next;
//数据域
T data;
//构造函数
Node()
{
this.data = null;
}
Node(T data)
{
this.data = data;
}
}
//头尾节点
private Node<T> head;
private Node<T> tail;
//链表的长度
private int length;
//该构造函数用于将链表头尾节点链接起来(初始化)
Bi_directLinklist()
{
//定义一个头节点、尾节点
this.head = new Node<T>();
this.tail = new Node<T>();
//将头尾节点的指针链接起来或者指向空
head.pre = null;
tail.next = null;
head.next = tail;
tail.pre = head;
this.length = 0;
}
// Bi_directLinklist(T data)
// {
// Node<T> tNode = new Node<T>(data);
//
// }
//添加节点(从前往后添加)
void pre_add(T data)
{
if(data==null)
{
throw new RuntimeException("第一个Node不能为空");
}
//申请一个节点
Node<T> tNode = new Node<T>(data);
//将节点添加到链表中
Node<T> temp = new Node<T>();
temp.next = head;
int i=0;
while(i < length)
{
temp = temp.next;
i = i+1;
}
//链接链表的时候一定要注意,这里的next是指针,不是节点,需要注意
tNode.pre = temp.next;
tNode.next = temp.next.next;
//注意这里的两句语句的顺序
tNode.next.pre = tNode;
temp.next.next = tNode;
this.length = length+1;
}
//遍历(从前往后遍历)正序遍历
void ergodic()
{
//申请一个临时节点
Node<T> temp = new Node<>(null);
//
temp.next = this.head;
while(temp.next!=null)
{
if(temp.next.data!=null)
{
System.out.println(temp.next.data);
}
//遍历链表时候需要注意这里
temp.next = temp.next.next;
}
System.out.println("一共"+this.length+"个节点");
}
//链表的查找
public T search(int index)
{
if(index>this.length)
{
throw new IndexOutOfBoundsException("索引越界");
}
//申请一个临时节点
Node<T> temp = new Node<>(null);
//
int i=0;
temp.next = this.head;
while(i<index)
{
temp = temp.next;
i++;
}
return temp.data;
}
}
注意这里再遍历链表时:temp.next = temp.next.next;
temp是一个移动的节点,因此每一次都是它的next指针域指向下一个节点,因此想要往下移动就需要使用它(temp)指向的节点(temp.next)的next