链表实现+面试题

单向链表

public class Node {
    public int value;
    public Node next;
    public Node(int data) {
        value = data;
    }
}

双向链表

public class DoubleNode {
    public int value;
    public Node next;
    public Node pre;
    public Node(int data) {
        value = data;
    }
}

第一题

问题描述:单链表反转

实例:a -> b -> c c -> b -> a

package com.lzf2.class02;

/**
 * 单链表反转
 */
public class LinkedInReversal {
    public static class Node{
        int value;
        Node next;
        public Node(Node next) {
            this.next = next;
        }
    }
    public static Node reversal(Node head){
        Node pree = null;
        Node curr = head;
        while (curr != null){
            Node next = curr.next;
            curr.next = pree;
            pree = curr;
            curr = next;
        }
        return pree;
    }   
}

第二题

问题描述:在链表中把给定值的结点都删除

实例:a->a->b->c->a 指定值a b->C

public class LinkedDeleteAll {
    public static class Node{
        int value;
        Node next;
        public Node(Node next) {
            this.next = next;
        }
    }

    public static Node delete(Node head,int val){
        while (head != null && head.value == val){
            head = head.next;
        }
        //head可能为null
        Node curr = head;
        Node pree = head;
        while (curr != null){
            if(curr.value == val){
                pree.next = curr.next;
            }else {
                pree = curr;
            }
            curr = curr.next;
        }
        return head;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值