双链表的头插头删及尾插尾删操作:
定义链表:
Node类:
public class Node {
int val;
Node next;
Node prev;
Node(int val, Node next,Node prev){
this.val=val;
this.next=next;
this.prev=prev;
}
Node(int val, Node next){
this.val=val;
this.next=next;
}
Node(int val){
this(val,null,null);
}
@Override
public String toString(){
return String.format("Null{%d}",val);
}
}
头插:
public class MyLinkedList2 {
Node head = null;
Node last = null;
int size = 0;
public Node pushFront(Node head,int val) {
Node node = new Node(val);
node.next = head;
if(head!=null) {
head.prev = node;
}
head = node;
if (head.next == null) {
last = head;
}
size++;
return head;
}
头删:
public Node popFront(Node head) {
if (size == 0) {
throw new RuntimeException("空了!");
}
head = head.next;
if (head != null) {
head.prev = null;
} else {
last = null;
}
size--;
return head;
}
尾插:
public Node pushBack(Node head,int val) {
Node node = new Node(val);
if (last != null) {
last.next = node;
node.prev = last;
last = node;
} else {
last = head = node;
}
size++;
return head;
}
尾删:
public void popBack() {
if (size == 0) {
throw new RuntimeException("空了!");
}
if (last.prev != null) {
last.prev.next = null;
last = last.prev;
} else {
head = last = null;
}
size--;
}
}
实现类:
public class UseList2 {
public static void print(Node head) {
Node cur = head;
while (cur != null) {
System.out.println(cur.val);
cur = cur.next;
}
}
public static void main(String[] args) {
Node head = null;
MyLinkedList2 h = new MyLinkedList2();
head=h.pushFront(head,5);
head=h.pushFront(head,4);
head=h.pushFront(head,3);
head=h.pushFront(head,2);
head=h.pushFront(head,1);
print(head);
head=h.popFront(head);
head=h.popFront(head);
head=h.popFront(head);
head=h.popFront(head);
print(head);
h.pushBack(head,4);
h.pushBack(head,3);
print(head);
h.popBack();
h.popBack();
print(head);
}
}
运行结果: