java实现双链表

mac2026-08-21  1

class Node{ public int data; public Node prev; public Node next; public Node(int data){ this.data = data; } } class DoubList { public Node head; public Node last; public DoubList(){ this.head = null; this.last = null; } public void addFirst(int data) { Node node = new Node(data); if (this.head == null) { this.head = node; this.last = node; } else { node.next = head; node.next.prev = node; this.head = node; } } public void addLast(int data) { Node node = new Node(data); if (this.head == null) { this.head = node; this.last = node; } else { this.last.next = node; node.prev = this.last; this.last = node; } } public int size(){ Node cur = this.head; int count = 0; while (cur != null){ count++; cur = cur.next; } return count; } private void cheackIndex(int index){ if(index < 0 || index > size()){ throw new IndexOutOfBoundsException("index不合法"); } } private Node searchIndex(int index){ int count = 0; Node cur = this.head; while (count<index){ cur = cur.next; count++; } return cur; } public boolean addIndex(int index,int data) { cheackIndex(index); if (index == 0) { addFirst(data); return true; } if (index == size()) { addLast(data); return true; } Node node = new Node(data); Node cur = searchIndex(index); node.next = cur; node.prev = cur.prev; cur.prev = node; node.prev.next = node; return true; } public boolean contains(int key){ Node cur = this.head; while (cur != null){ if(cur.data == key){ return true; } cur = cur.next; } return false; } //删除第一次出现的关键字 并返回删除的元素 public int remove(int key){ Node cur = this.head; int oldData = -1; while (cur != null) { if (cur.data == key) { oldData = cur.data; if (cur == this.head) { this.head = cur.next; this.head.prev = null; } else { if (cur.next != null) { cur.next.prev = cur.prev; } else { this.last = cur.prev; } cur.prev.next = cur.next; } return oldData; } cur = cur.next; } return oldData; } public void removeAllKey(int key){ Node cur = this.head; while (cur != null){ if(cur.data == key){ if(cur == this.head){ this.head = cur.next; if(this.head != null) this.head.prev = null; }else{ if(cur.next != null){ cur.next.prev = cur.prev; }else{ this.last = cur.prev; } cur.prev.next = cur.next; } } cur = cur.next; } } public void display(){ Node cur = this.head; while (cur != null){ System.out.print(cur.data+ " "); cur = cur.next; } System.out.println(); } public void clear(){ Node cur = this.head; while (cur != null){ Node curNext = cur.next; cur.prev = null; cur.next = null; cur = curNext; } this.head = null; this.last = null; } }
最新回复(0)