链表(LinkedList)

1.链表的原理

属于一种线性表
1.元素和元素直接有相对顺序的
2.有头部/尾部
3.prev / cur / next
不同于顺序表:
逻辑上存在线性结构,但不保证物理满足该次序
在这里插入图片描述
链表的结点定义:

public class Node {
    int val;
    Node next;
    
    public Node(int val) {
        this.val = val;
        this.next = null;
   }
    
    @Override
    public String toString() {
        return "Node{" + val + "}";
   }
}

创建一个 [1 3 2 6] 的链表 :

Node n1 = new Node(1);
Node n3 = new Node(3);
Node n2 = new Node(2);
Node n6 = new Node(6);
n1.next = n3;
n3.next = n2;
n2.next = n6;
n6.next = null;
Node head = n1 ;

头插

  public static Node pushFront(Node head, int val){
        Node node =  new Node(val);
         node.next  =  head  ;
         return   node ;
    }

头删
假定不为空结点

 public static Node popFront(Node head) {
        return  head.next;
    }

尾插

private static Node pushBack(Node head, int v) {
    if (head == null) {
        Node node = new Node(v);
        return node;
   }
    
    Node last = head;
    while (last.next != null) {
        last = last.next;
   }
    
    Node node = new Node(v);
    last.next = node;
    
    return head; }

尾删

 private static Node popBack(Node head) {
        // head != null
        if (head.next == null) {
            return null;
        } else {
            Node last = head;
            while (last.next.next != null) {
                last = last.next;
            }
            // last 是最后一个结点
            last.next = null;

            return head;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值