当前位置: 移动技术网 > IT编程>开发语言>Java > Java实现双向链表(两个版本)

Java实现双向链表(两个版本)

2019年07月22日  | 移动技术网IT编程  | 我要评论

临近春节,项目都结束了,都等着回家过年了。下面是小编给大家研究数据结构的相关知识,链表算是经常用到的一种数据结构了,现将自己的实现展示如下,欢迎大神赐教。

第一个版本,没有最后一个节点,每次从根节点开始遍历

public class linkedlist<e> {
private node head;
public linkedlist() {
}
public e getfirst(){
if(head==null){
return null;
}
return head.value;
}
public linkedlist<e> addfirst(e e){
head.pre=new node(e, null, head);
head=head.pre;
return this;
}
public linkedlist<e> addnode(e e){
node lst=head;
if(lst==null){
this.head=new node(e, null, null);
return this;
}else{
while(true){
if(lst.next==null){
break;
}else{
lst=lst.next;
}
}
lst.next=new node(e, lst, null);
return this;
}
}
public linkedlist<e> remove(e e){
node lst=head;
if(lst==null){
throw new nullpointerexception("the linkedlist is empty.");
}else{
while(true){
if(e.equals(lst.value)){
//移除这个元素
if(lst.pre!=null){
lst.pre.next=lst.next;
}
if(lst.next!=null){
lst.next.pre=lst.pre;
}
lst=null;
break;
}
lst=lst.next;
}
return this;
}
}
@override
public string tostring() {
stringbuffer buff=new stringbuffer("[");
node lst=this.head;
while(lst!=null){
buff.append(lst.value+",");
lst=lst.next;
}
return buff.substring(0, buff.length()-1)+"]";
}
/**节点信息*/
private class node{
public node pre;
public e value;
public node next;

public node(e value,node pre,node next) {
this.value=value;
this.pre=pre;
this.next=next;
}
} 
}

第二个版本,有了最后一个节点

public class linkedlist<e> {
private node head;
private node last;
public linkedlist() {
}
public e getfirst(){
if(head==null){
return null;
}
return head.value;
}
public e getlast(){
if(last==null){
return null;
}
return last.value;
}
public linkedlist<e> addfirst(e e){
head.pre=new node(e, null, head);
head=head.pre;
return this;
}
public linkedlist<e> addnode(e e){
node lst=last;
if(lst==null){//如果最后一个节点是空的则这个链表就是空的
this.last=new node(e, null, null);
this.head=this.last;
return this;
}else{
while(true){
if(lst.next==null){//
break;
}else{
lst=lst.next;
}
}
lst.next=new node(e, lst, null);
last=lst.next;
return this;
}
}
public linkedlist<e> remove(e e){
node lst=head;
if(lst==null){
throw new nullpointerexception("the linkedlist is empty.");
}else{
while(true){
if(e.equals(lst.value)){
//移除这个元素
if(lst.pre!=null){
lst.pre.next=lst.next;
}
if(lst.next!=null){
lst.next.pre=lst.pre;
}
lst=null;
break;
}
lst=lst.next;
}
return this;
}
}
@override
public string tostring() {
stringbuffer buff=new stringbuffer("[");
node lst=this.head;
while(lst!=null){
buff.append(lst.value+",");
lst=lst.next;
}
return buff.substring(0, buff.length()-1)+"]";
}
/**节点信息*/
private class node{
public node pre;
public e value;
public node next;

public node(e value,node pre,node next) {
this.value=value;
this.pre=pre;
this.next=next;
}
}
}

注:以上两个版本都没有考虑在多线程下使用的情况。

以上所述是小编给大家介绍的java实现双向链表(两个版本)的相关知识,希望对大家有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网