您的位置:首页 > 理论基础 > 数据结构算法

【数据结构和算法分析】双链表的增,删操作

2014-07-25 15:28 309 查看

双链表的增,删操作

双链表:单链表的结点中只有一个指向直接后继结点的指针,所以,从某个结点出发只能顺着指针往后查询其他的结点靠,那如果我想访问某个结点的前一个结点,岂不只能重新从表头结点开始了?效率真低啊!换句话说,在单链表中,getNext()的时间复杂度为O(1),而getPrior()的时间复杂度则为O(N)。为克服单链表这种单向性的缺点,我们可以利用双链表。

public class MyDulList {

/*
* 双向链表的基本实现
* 包括插入结点,删除结点,查询某一位置结点的值,修改结点的值,反回结点的位置等基本功能
*/
Node headNode;
Node tailNode;
int length;

/*
* 由结点初始化,该结点既是头结点,也是尾结点
*/
public MyDulList(Node node){
this.headNode = node;
this.tailNode = node;
length = 1;
}
/*
* 双向链表的增加结点
* @param Node node 增加的结点
*/
public void insert(Node node){
insert(node,length);
}
/*
* 双向链表的增加结点
* @param Node node 增加的结点  int index 增加的位置
*/
public void insert(Node node,int index){
if (index < 0 || index > length) {
throw new IndexOutOfBoundsException();
}
if(index == 0){
node.next = this.headNode;
this.headNode.prior = node;
headNode = node;
}else if (index == length) {
this.tailNode.next = node;
node.prior = this.tailNode;
tailNode = node;
}else{
Node otherNode = headNode;
while (index > 1) {
otherNode = otherNode.next;
index--;
}
node.next = otherNode.next;
otherNode.next.prior = node;
otherNode.next = node;
node.prior = otherNode;
}
length++;
}
/*
* 双向链表删除结点
* @param int index 删除结点的位置
*/
public void delete(int index){
if (index < 0 || index >= length) {
throw new IndexOutOfBoundsException();
}
if (index == 0 && length == 1) {
this.headNode = this.tailNode = null;
}else if (index == 0 && length != 1) {
this.headNode.next.prior = null;
headNode = this.headNode.next;
}else {
Node otherNode = this.headNode;
while (index > 1) {
otherNode = otherNode.next;
index--;
}
if(otherNode.next.next != null){
otherNode.next = otherNode.next.next;
otherNode.next.prior = otherNode;
}else {
otherNode.next = null;
this.tailNode = otherNode;
}
}
length--;
}
public void show(){
Node otherNode = this.headNode;
while (otherNode.next != null) {
System.out.print(otherNode.data+" ");
otherNode = otherNode.next;
}
System.out.println(otherNode.data);
}

/*
* 利用 prior 反向输出链表
*/
public void show_re(){
Node otherNode = this.tailNode;
while (otherNode.prior != null) {
System.out.print(otherNode.data+" ");
otherNode = otherNode.prior;
}
System.out.println(otherNode.data);
}
}

class Node{
/*
* 节点类,包括结点的值 data ,指向下一结点的指针 next,指向前一结点的指针 prior
*/
Object data;
Node prior;
Node next;

public Node(){
this.data = null;
this.prior = null;
this.next = null;
}
public Node(Object data){
this.data = data;
this.prior = null;
this.next = null;
}
public Node(Object data,Node prior,Node next){
this.data = data;
this.prior = prior;
this.next = next;
}
public boolean hasprior(){
return this.prior != null;
}
public boolean hasnext(){
return this.next != null;
}
public Node getNext(){
return this.next;
}
public Node getPrior(){
return this.prior;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: