链表
链表是指一种物理存储结构上非连续,非顺序的存储结构,数据元素的逻辑顺序是通过链表中的引用链接次序实现的
-
头插
1.若插入的数据没有结点,现将数据写入一个新的结点
Node node=new node();
node.value=要写入结点的值;
2.让新结点的下一个结点为原来的第一个结点
node.next=head;
3.更新新的头结点
head=node;
-
尾插(尾插需要考虑当前链表是否为空链表)
当前链表非空链表
1.将要插入的结点值装入新节点中,并将它的next值置为空(因为在构造方法中已经实现)
Node node=new Node(val);
2.便利整个链表找到链表的最后一个元素
Node last=head;//从头开始遍历
while(last.next!=null){
last=last.next;
}
3.让最后一个结点的next指向node
last.next=node;
如果当前链表为空链表,则直接让head=node;
-
头删
头删直接
head=head.next
-
尾删
尾删需要让倒数第二个元素的next为null,所以链表至少要有两个结点
空链表
if(head==null)
Sysyem.out.println("空链表无法删除");
链表中有一个结点
head==null;
链表中至少有两个结点(先遍历找到倒数第二个结点,将它的next置为null
Node lastsecond-head;
while(lastsecond.next.next!=null)
lastsecond=lastsecond.next;
lastsecond.next=null;
完整的代码
class Node{
int val;
Node next;
public Node(int val){
this.val=val;
this.next=null;
}
}
public class MyLinkedList{
public static void main(String[] args){
Node head=null;
int val=0;
head=pushBack(head,0);
head=pushBack(head,1);
head=pushFront(head,2);
print(head);//2 0 1
head = pushBack(head, 10);
head = pushBack(head, 20);
print(head); // 2 0 1 10 20
head = popBack(head);
head = popBack(head);
head = popBack(head);
head = popBack(head);
head = popBack(head);
head = popBack(head); // 报错
print(head); // 空
head = pushBack(head, 100);
print(head); //100
}
public static Node pushFront(Node head,int val){
Node node=new Node(val);
node.next=head;
return node;
}//头插
public static Node pushBack(Node head,int val){
Node node=new Node(val);
if(head==null)
return node;//空链表时进行尾插会改变头结点
else {
Node last=head;
while(last.next!=null){//找到最后一个结点
last=last.next;
}
last.next=node;
return head;
}
}//尾插
public static void print(Node head){
Node cur=head;
while(cur!=null){
System.out.println(cur.val);
cur=cur.next;
}
}//遍历访问结点
public static Node popFront(Node head){
if(head==null){
System.out.println("空链表无法删除");
return head;
}
head=head.next;
return head;
}//头删
public static Node popBack(Node head){
if(head==null){
System.out.println("空链表无法删除");
return head;
}
if(head.next==null)
return null;
else{
Node lastsecond=head;
while(lastsecond.next.next!=null){//找到倒数第二个结点
lastsecond=lastsecond.next;
}
lastsecond.next=null;
return head;
}
}//尾删
}