《算法通关村第一关——链表青铜挑战笔记》


一、链表的构造

使用递归和for循环将数组转换为列表

public class MakeLink {
    public static void main(String[] args) {
        int arr[] ={1,2,3,4,5,6};
        Node n1 = madelink(arr,0);
        Node n2 = madelink(arr);
        while (n!=null){
            System.out.println(n.val);
            n = n.next;
        }
    }
    //递归
    public static Node  madelink(int arr[],int start){

        if(start == arr.length){
            return null;
        }
        return new Node(arr[start],madelink(arr,++start));
    }
    //for循环
    public static Node madelink(int arr[]){
    	//使用虚拟头节点
        Node node = new Node(-1,null);
        Node next=node;
        for(int i=0;i<arr.length;i++){
            next.next=new Node(arr[i],null);
            next=next.next;
        }
        return node.next;
    }
}
class Node{
     int val;
     Node next;

    public Node(int val, Node next) {
        this.val = val;
        this.next = next;
    }
}


二、链表元素的增加

在头部,中间和尾部三个位置添加元素

	//在头部添加元素
    public static Node increaseHead(Node node,int val){
        return new Node(val,node);
    }
    //在中间添加元素
    public static Node increaseBody(Node node,int val,int position){
        Node next=node;
        if(position==1){
            return new Node(val,node);
        }
        for(int i=1;i<position-1;i++){
            next=next.next;
        }
        next.next=new Node(val,next.next);
        return node;
    }
    在尾部添加元素
    public static Node increaseLast(Node node,int val){
        Node next = node;
        while (next.next!=null){
            next=next.next;
        }
        next.next=new Node(val,null);
        return node;
    }

三、双向链表构造

//相比于单向链表只多了一个前驱,添加和删除的方法加上对应的前驱即可
class DNode{
    int val;
    Node pre;
    Node next;
    
    public DNode(int val, Node pre,Node next) {
        this.pre=pre;
        this.val = val;
        this.next = next;
    }

总结

1.利用虚拟头节点保存第一个节点的地址,避免"黑瞎子掰苞米"的问题
2.插入(删除)节点时要想好循环次数与插入(删除)位置的关系
3.在遍历链表到尾部时,控制好边界,避免指向空

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值