package LinkList.doublelinklist; public class Node { public int data;//数据域 public Node next;//结点域,下一个结点 public Node prve;//结点域,前一个结点 //头结点初始化 public Node(Node next){ this.data=data; this.next=next; this.prve=null; } //非头结点初始化 public Node(int data,Node next,Node prve){ this.data=data; this.next=next; this.prve=prve; } }
************************************************************************************************************************************
package LinkList.doublelinklist; public class DoubleLinkList { Node head;// 头结点 int size;// 链表大小 Node current;// 当前结点 // 初始化空链表 public DoubleLinkList() { this.head = new Node(null); this.size = 0; this.current = head; } // 判断线性表是否为空 public boolean isEmpty() { return size == 0; } // 获取指定位置的元素,这里我们定义头结点head的index为-1 public Node getElement(int index) { if (index < -1 || index >= size) { throw new RuntimeException("参数错误"); } if (index == -1) { current = head; } else { current = head.next; } for (int i = 0; i < index && current.next != null; i++) { current = current.next; } return current; } // 在指定位置插入元素,这里我们定义头结点head的index为-1 public void insert(int index, int data) { Node node = new Node(data, null,null); Node prev = getElement(index - 1);// 当前结点的前一个结点 current=prev.next;//当前结点 if(current!=null){ node.prve=prev; node.next=current; current.prve=node; prev.next=node; }else{ node.prve=prev; node.next=current; prev.next=node; } size++; } // 删除指定位置的元素 public void delete(int index) { if (index > size - 1) { throw new RuntimeException("参数错误"); } Node prev = getElement(index - 1);// 当前结点的前一个结点 current = prev.next; prev.next = current.next; current.prve = prev; size--; } // 打印链表 public void traverse() { if (isEmpty()) { System.out.println("null"); } else { current = head.next; while (current != null) { System.out.print(current.data + " "); current = current.next; } System.out.println(); } } }
时间: 2024-10-27 10:05:41