链表的基础操作–对于边界条件的思考

1.反转链表

public static class Lnode{
    public int value;
    public Lnode next;

    public Lnode(int value) {
        this.value = value;
    }
}

/**
    * 反转链表
    * @param head
    * @return
    */
public Lnode reverseLnode(Lnode head){
    Lnode pre = null;
    Lnode next = null;
    while (head != null){
        next = head.next;
        head.next = pre;
        pre = head;
        head = next;
    }
    return  pre;
}

/**
    * 删除链表中值为val的节点
    * @param head
    * @param val
    * @return
    */
public Lnode deleteLnode(Lnode head, int val){
    // 将头节点清空
    while (head != null){
        if (head.value != val){
            break;
        }
        head = head.next;
    }

    // head == null or head != null
    Lnode pre = head;
    Lnode cur = head;
    while (cur != null){
        // 如果当前节点值相同,则前置节点指向当前节点的下一个节点
        if (cur.value == val){
            pre.next = cur.next;
        }else {
            // 如果不同则直接前置节点向后移动
            pre = cur;
        }
        // 保持当前节点始终在前置节点之后
        cur = cur.next;
    }
    // 返回节点头部
    return head;
}

2.数组实现队列

public class ArrToQueue {
    public int[] arr;
    public int limit;
    public int end;
    public int begin;
    public int size;

    public ArrToQueue(int limit) {
        this.arr = new int[limit];
        this.end = 0;
        this.begin = 0;
        this.size = 0;
    }

    /**
     * 向队列中放入元素
     * @param val
     */
    public void pull(int val){
        if (size == limit){
            System.out.println("队列满了!");
            return;
        }
        arr[end] = val;
        size++;
        end = nextIndex(end);
    }

    /**
     * 队列中弹出元素
     * @return
     */
    public int pop(){
        if (size == 0){
            System.out.println("队列为空");
        }
        int ans = arr[begin];
        size--;
        begin = nextIndex(begin);
        return ans;
    }

    /**
     * 判断队列是否为空
     * @return
     */
    public boolean isEmpty(){
        return size == 0;
    }

    /**
     * 判断下标是否到达最后一个,若是的话返回0,不是的话返回自身
     * @param index
     * @return
     */
    public int nextIndex(int index){
        return index < limit - 1 ? index+1 : 0;
    }
}