链表
1.逻辑上有前后顺序
2.不保证逻辑前后顺序的元素挨着
一、学会遍历链表(完整遍历)
for(Node cur=head;cur!=null;cur=cur.next){}
Node cur=head;
while(cur!=nulll){
cur=cur.next;
}
二、功能
1.增
1)头插
//第一步:申请新节点
Node newNode=new Node(value);
//第二步:更新newNode的next
newNode.next=head;
//第三步:更新head
//head=newNode; //做了没什么影响,通常不做
return newNode;
2)尾插
注意:链表为空,视为头结点
链表不为空,为下:
//第一步:申请新节点,并且让next=null
Node newNode=new Node(value);
//第二步:找到当前链表的最后一个结点
Node last=getLest(head);
//第三步:让最后一个结点的next=value
last.next=newNode;
return newNode;
2.删
1)头删
删除当前链表的第一个结点,直接返回链表的第二个值,即 retrun head.next;
2)尾删
只有一个节点的删除,视为头删;
大于两个节点的删除:
第一步:找到倒数第二个结点
第二步:倒数第二个结点的next=null
第三个:释放原最后一个结点
代码表示:
//链表的基本操作
public class Main {
//遍历链表
public static void displayLinkedList(Node head){
for(Node cur=head;cur!=null;cur=cur.next){
System.out.printf("(%d)->",cur.value);
}
System.out.println("null");
}
//创建链表
public static Node createLinkedList() {
Node n1 = new Node(1); // 首结点(头结点)
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = null;
return n1;
}
//链表头插
public static Node pushFront(Node head,int value){
Node newNode=new Node(value);
newNode.next=head;
//head=newNode;
return newNode;
}
//链表尾插
public static Node pushBack(Node head,int value){
if(head==null){
return pushFront(head,value);
}
else{
Node newNode=new Node(value);
Node last=getLast(head);
last.next=newNode;
return head;
}
}
//找最后一个结点
private static Node getLast(Node head) {
Node cur=head;
while(cur.next!=null){
cur=cur.next;
}
return cur;
}
//链表头删
public static Node popFront(Node head){
if(head==null){
System.out.println("参数不合法");
return null;
}
return head.next;
}
//链表尾删
public static Node popBack(Node head){
if(head==null){
System.out.println("参数不合法");
return null;
}
if(head.next==null){
return null;
}
else{
Node lastLast=getLastLast(head);
lastLast.next=null;
return null;
}
}
//找倒数第二个结点
private static Node getLastLast(Node head) {
Node cur=head;
while(cur.next.next!=null){
cur=cur.next;
}
return cur;
}
public static void main(String[] args) {
Node head=createLinkedList();
displayLinkedList(head);
head = pushFront(head, 100);
displayLinkedList(head);
pushBack(head,200);
displayLinkedList(head);
head=popFront(head);
displayLinkedList(head);
popBack(head);
displayLinkedList(head);
}
}
空链表:一个节点都没有的链表
区别以下链表表示:
- n1=n2;(绿色表示)
- n1.next=n2;(黄色表示)
- n1=n2.next;(紫色表示)
- n1.next=n2.next;(红色表示)
注意:链表中多做题,多画图表示