版权声明:无意呢。 https://blog.csdn.net/qq_41900081/article/details/86546989
双链表的优点:
对于链表中的一个结点,拥有两个指针,一个指向前驱结点,一个指向后继结点,因此可以从两个方向继续操作
双链表的缺点:
1) 每个结点需要议案家一个额外的指针,因此需要更多的空间开销
2)结点的插入或删除操作更加费时(需要更多的指针操作)、
双链表的基本操作
- 插入操作
1)前插
2)尾插
3)中间插入- 删除操作
1)删除头结点
2)删除尾结点
3)删除中间结点
Java代码实现
package dataStructure;
class DDLNode{
int data;
DDLNode previous = null;
DDLNode next = null;
public DDLNode(int d) {
data = d;
}
}
public class DDList{
//头结点
DDLNode head;
public DDList() {
head = null;
}
//获取双链表长度
int size() {;
if(head == null) return 0;
int len = 1;
DDLNode cur = head;
while(cur.next != null) {
len++;
cur = cur.next;
}
return len;
}
//打印双链表
void Print() {
DDLNode cur = head;
if(cur == null) System.out.println("null");
while(cur != null) {
System.out.print(cur.data+"->");
cur = cur.next;
}
System.out.println();
}
//插入结点
DDLNode Insert(DDLNode node,int position) {
DDLNode pre = head;
//双链表为空
if(head == null) {
if(position != 1) {
System.out.println("非法插入");
return head;
}
head = node;
return head;
}
//非法插入
if(position < 1 || position > size()+2) {
System.out.println("非法插入");
return head;
}
if(position == 1) {
node.next = pre;
pre.previous = node;
head = node;
return head;
}else {
int count = 1;
//找到插入的位置
while(count < position - 1) {
pre = pre.next;
count++;
}
DDLNode cur = pre.next;
node.next = cur;
pre.next = node;
node.previous = pre;
if(cur != null)
cur.previous = node;
}
return head;
}
//删除指定结点
DDLNode deleteDDLNode(int position) {
if(head == null) {
System.out.println("双链表为空,不允许删除");
return head;
}
if(position > size() || position < 1) {
System.out.println("非法删除");
return head;
}
if(position == 1) {
DDLNode del = head;
head = head.next;
head.previous = null;
return del;
}else {
DDLNode pre = head;
int count = 1;
while(count < position - 1) {
pre = pre.next;
count++;
}
DDLNode del = pre.next;
pre.next = del.next;
if(del.next != null)
del.next.previous = pre;
del.next = null;
del.previous = null;
return del;
}
}
public static void main(String[] args) {
DDList list = new DDList();
list.Insert(new DDLNode(1), 1);
list.Insert(new DDLNode(2), 2);
list.Insert(new DDLNode(5), 2);
list.Print();
list.deleteDDLNode(3);
list.Print();
}
}