链表可以进行各种操作,例如头插,头删,尾插及尾删等,这些操作具体实现如下:
先用一个Node类来定义链表:
public class Node {
int val;
Node next;
Node(int val, Node next){
this.val=val;
this.next=next;
}
Node (int val){
this(val,null);
}
@Override
public String toString(){
return String.format("Null{%d}",val);
}
}
实现头插:
public class MyLinkedList1 {
Node head=null;
Node last=null;
int size=0;
public Node pushFront(Node head, int val){
head=new Node(val,head);
size++;
return head;
}
头删:
public Node popFront(Node head){
if(head==null){
throw new RuntimeException("空了!");
}
head=head.next;
size--;
return head;
}
尾插:
public void pushBack(Node head, int val){
Node node =new Node(val);
if(head==null){
head=null;
}else{
last=head;
while(last.next!=null){
last =last.next;
}
last.next=node;
last=last.next;
size++;
}
}
尾删:
public void popBack(Node head){
if(head==null){
throw new RuntimeException("空了!");
}else{
Node prevlast=head; //prev为倒数第二个结点
while(prevlast.next.next!=null){
prevlast=prevlast.next;
}
prevlast.next=null;
size--;
}
}
定义类去实现这些操作:
public class UseList1 {
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;
MyLinkedList1 h=new MyLinkedList1();
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(head);
h.popBack(head);
print(head);
}
}
运行结果:
其中前五行为头插操作;
第五行为头删操作;
第6, 7, 8行为尾插操作;
第9行为尾删操作。