算法通关——初识链表

构建链表(java)

leetcode常见构建方式
public class ListNode{
    public int val;
    public ListNode next;
    ListNode(int x){
        val=x;
        next=null;
    }
    
}
ListNode listnode=new ListNode(1);


链表基础操作

遍历

注意不要丢掉head节点

public static int getListLength(Node head){
    int length=0;
    Node node=head;
    while(node!=null){
        length++;
        node=node.next;
    }
    return length;
}

插入

头部插入

假设要插入的新节点newNode,执行newNode.next=head即可与旧链表表头连接,然后执行head=newNode重置表头

中间插入

如图例,假设new要插入 15 和 7 之间,那么要处理两个节点的next:先执行new.next=node(7),再执行node(15).next=new即可(先客后主原则!)

注意若先执行 node(15).next=new,链表将发生断裂,也会是说将找不到node(15)后面的节点

尾部插入

尾节点导向新节点即可, new.next=null , lastNode.next=new

插入节点代码
/**
    *链表插入
    *@param head 链表头节点
    *@param nodeInsert 待插入节点
    *@param position 待插入位置,始于1
    *@return 插入函数完成后返回链表头节点
 */
public static Node insertNode(Node head,Node nodeInsert,int position){
    //待插入节点即链表头节点,排除
    if(head == null){
        return nodeInsert;
    }
    //链表已经存放的元素个数
    int size = getLength(head);
    //排除插入位置为链表外部
    if(position > size+1 || position < 1){
        System.out.println("位置参数越界")
        return head; 
    }

    //表头插入
    if(position == 1){
        nodeInsert.next = head;//原表头接在插入节点后面
        head = nodeInsert;//将插入节点任命为新表头
        return head;
    }
    //非表头插入
    Node pNode = head;//pNode为插入准备
    int count = 1;
    while(count < postion - 1){
        pNode = pNode.next;
        count++ ;
    }//循环完毕,至此pNode为要插入位置的前一个节点
    nodeInsert.next = pNode.next;//先继承信息避免链表断裂
    pNode.next = nodeInsert;//接入
    return head;
}

删除

头节点删除

head = head.next即可

中间节点删除

要提前判断,找出目标节点的前驱节点cur,执行cur.next = cur.next.next 即可(跳过要删除的节点)

尾部节点删除

要提前判断,找出目标节点的前驱节点cur

如图,要删除尾部节点node(40),此时cur为node(7),那么执行cur.next = null 即可。JVM会回收node(40).

删除节点代码
/**
    *删除节点
    *@param head 
    *@param postion
    *@return  返回删除后的链表头节点
 */
 public static Node deleteNode(Node node ,int position){
     if(head == null){
         return null 
     }
     int size = getListLength(head);
     if(postion > size || position < 1){
         System.out.println("插入参数有误");
         return head;
     }
     if(postion==1){
         return head.next;
     }
     else//非表头删除
     {
         Node cur = head;
         int count = 1;
         while(count < postion - 1){
             cur = cur.next;
             count++;
         }
         cur.next = cur.next.next;
     }
     return head;
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值