双向链表
package DoubleList;
public class DoubleList {
class ListNode {
public int data;
public ListNode next;
public ListNode prev;
public ListNode(int data) {
this.data = data;
}
}
public ListNode head;
public ListNode last;
public void addFirst(int data){
ListNode node = new ListNode(data);
if(this.head == null) {
this.head = node;
this.last = node;
}else {
node.next = this.head;
this.head.prev = node;
this.head = node;
}
}
public void addLast(int data){
ListNode node = new ListNode(data);
if(this.head == null) {
this.head = node;
this.last = node;
}else {
this.last.next = node;
node.prev = this.last;
this.last = node;
}
}
public void display(){
ListNode cur = this.head;
while (cur != null) {
System.out.print(cur.data+" ");
cur = cur.next;
}
System.out.println();
}
private ListNode searchIndex(int index) {
if(index < 0 || index >= size()) {
return null;
}
ListNode cur = this.head;
while (index > 0) {
cur = cur.next;
index--;
}
return cur;
}
public void addIndex(int index,int data){
if(index == 0) {
addFirst(data);
return ;
}
if(index == size()) {
addLast(data);
return ;
}
ListNode node = new ListNode(data);
ListNode cur = searchIndex(index);
if(cur == null) {
return ;
}
node.next = cur;
cur.prev.next = node;
node.prev = cur.prev;
cur.prev = node;
}
public int size(){
ListNode cur = this.head;
int count = 0;
while (cur != null) {
count++;
cur = cur.next;
}
return count;
}
public boolean contains(int key){
ListNode cur = this.head;
while (cur != null) {
if(cur.data == key) {
return true;
}
cur = cur.next;
}
return false;
}
public int remove(int key){
ListNode cur = this.head;
while (cur != null) {
if(cur.data == key) {
int oldData = cur.data;
if(cur == this.head) {
this.head = this.head.next;
this.head.prev = null;
}else {
cur.prev.next = cur.next;
if(cur.next != null) {
cur.next.prev = cur.prev;
}else {
this.last = cur.prev;
}
}
return oldData;
}
cur = cur.next;
}
return -1;
}
public void removeAllKey(int key){
ListNode cur = this.head;
while (cur != null) {
if(cur.data == key) {
if(cur == this.head) {
this.head = this.head.next;
this.head.prev = null;
}else {
cur.prev.next = cur.next;
if(cur.next != null) {
cur.next.prev = cur.prev;
}else {
this.last = cur.prev;
}
}
}
cur = cur.next;
}
}
public void clear(){
while (this.head != null) {
ListNode cur = this.head.next;
this.head.next = null;
this.head.prev = null;
this.head = cur;
}
this.last = null;
}
}