Java双链表的设计
public class Node {
public int data;
public Node prev;
public Node next;
public Node(){
}
public Node (int data){
this.data = data;
}
}
package Double_linked_list;
public class MyLinkedList {
public Node head;
public MyLinkedList(int i){
head = new Node(i);
}
public boolean deleteAtIndex(int index){
Node temp = head;
int i = 0;
while (temp.next != null){
if (index == i){
temp.prev.next = temp.next;
temp.next.prev = temp.prev;
return true;
}
temp = temp.next;
i++;
}
return false;
}
public Node addAtIndex(int index,int data){
if (index <= 0){
addAtHead(data);
return head;
}
Node tempA = head;
int i = 0;
while (tempA.next != null){
i++;
tempA = tempA.next;
}
if (index > i){
return null;
}
if (index == i){
addAtTail(data);
return head;
}
else {
Node tempB =head;
int j = 0;
while (tempB.next != null){
if (j == index){
Node node = new Node(data);
node.prev = tempB.prev;
node.next = tempB;
tempB.prev.next = node;
tempB.prev = node;
return node;
}
tempB = tempB.next;
j++;
}
}
return null;
}
public Node addAtHead(int data){
Node node = new Node(data);
Node temp = head;
temp.prev = node;
node.next = temp;
head = node;
return head;
}
public Node get(int index){
Node temp = head;
int i = 0;
if (index == 0){
return temp;
}
while (temp.next != null){
temp = temp.next;
i++;
if (index == i){
return temp;
}
}
return null;
}
public void addAtTail(int data){
Node temp = head;
while (temp.next != null){
temp = temp.next;
}
Node node = new Node(data);
node.prev = temp;
temp.next = node;
}
public void print(){
Node temp = head;
while (temp != null){
System.out.print(temp.data+",");
temp = temp.next;
}
System.out.println();
}
}