java学习经验总结------双向链表的实现
双向链表的建立与单链表类似,只是需要使用pre指针指向前一个结点,并且在删除添加时不仅仅考虑next
package datastructure;
public class DoubleLinkedList {//双向链表的构造使用
public static void main(String[] args) {
// TODO 自动生成的方法存根
DoubleList dl = new DoubleList();
dl.empty_add("5");
dl.empty_add("3");
dl.empty_add("2");
dl.empty_add("1");
dl.insert(2, "8");
dl.orderprint();
dl.reverseorderprint();
}
}
class DoubleList{
public Dlnode first;//头指针
public Dlnode current;//当前结点
private int count=0;//结点个数
public DoubleList() {
// TODO 自动生成的构造函数存根
this.first=new Dlnode(null);
current=first;
first.next=null;
}
public int getCount() {//得到结点个数
return count;
}
public void empty_add(String word) {//由空链表添加结点
Dlnode newnode = new Dlnode(word);
//current=first;
while(current.next!=null)
current=current.next;
current.next=newnode;
newnode.pre=current;
newnode.next=null;
current=current.next;
this.count++;
}
public void orderprint() {//按照顺序遍历
Dlnode now;
for(now=first.next;now!=null;now=now.next)
System.out.print(now.getWord());
if(now==null)
System.out.println("null");
System.out.println("结点个数为:"+this.getCount());
/*System.out.println(current.getWord());*/
}
public void reverseorderprint() {//按照逆序遍历
while(current!=null)
{
System.out.print(current.getWord());
current=current.pre;
}
System.out.println("结点个数为:"+this.getCount());
}
public void insert(int location,String word) {//在指定地点插入
if(location>count)
System.out.println("已超过结点个数,无法插入!!!");
else {
Dlnode now=first;
while(true) {
if(location==0)
break;
else {
now=now.next;
location--;
}
}
Dlnode temp = new Dlnode(word);
now.pre.next=temp;
temp.pre=now.pre;
now.pre=temp;
temp.next=now;
this.count++;
}
}
/*public void delete(int location) {//删除功能留置,与添加类似
if(location>count)
}*/
}
class Dlnode{//链表结点
private String word;
public Dlnode pre;
public Dlnode next;
public Dlnode(String word) {
// TODO 自动生成的构造函数存根
this.word=word;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
}