线性表

顺序存储线性表(数组实现)

public class Sqlist {

    static int [] table;
    static int n;
    
    public Sqlist(int n)
    {
        table=new int[n];
        this.n=0;
    }
    
    public boolean isEmpty()
    {
        return n==0;
    }
    
    public boolean isFull()
    {
        return n>=table.length;
    }
    
    public int getcapacity()
    {
        return table.length;
    }
    
    public int getlength()
    {
        return n;
    }
    
    //ADD
    public void addElem(int loc,int value)
    {
        if(n>=table.length)
        {
            System.out.println("数组满了");
        }
        if((loc<1)||(loc>table.length))
        {
            System.out.println("插入位置错误");
        }
        if(loc<=n+1)
        {
            for(int i=n-1;i>=loc;i--)
            {
                table[i+1]=table[i];
            }
            table[loc-1]=value;
            n++;
            System.out.println("插入成功,在第"+loc+"个位置之前插入:"+value);
        }
        
    }
    
    //DELETE
    public int getElem(int i)
    {
        if((i<1)||(i>table.length))
        {
            return -1;
        }
        else {
            return table[i-1];
        }
    }
}

 

 

链式存储 单链表 (头插法、尾插法)

import java.util.Random;


//结点
public class ListNode {

    public int value;
    public ListNode next;
    public ListNode(int data)
    {
        this.value=data;
    }    
    
}


class MySinglelinkedList
{
    private static ListNode head;
    private static ListNode tail;
    private static int length=0;
    
    public void init()
    {
        
    }
    
    public void print()
    {
        ListNode temp=head;
        while (temp!=null) {
            System.out.println(temp.value);
            temp=temp.next;
        }
    }
    
    
    
    
    //头插法
    public void addNode()
    {
        Random random=new Random();
        head=null;
        for(int i=0;i<20;i++)
        {
            int temp=random.nextInt(100);
            ListNode newNode=new ListNode(i);
            length++;
            if(head==null)
            {
                head=newNode;
            }
            else {
                newNode.next=head.next;
                head.next=newNode;
            }
        }
    }
    
    
    //尾插法
    public void addNode1()
    {
        tail=head=null;
        for(int i=0;i<20;i++)
        {
            ListNode newNode=new ListNode(i);
            length++;
            if(head==null)
            {
                head=tail=newNode;
            }
            else
            {
                tail.next=newNode;
                tail=newNode;
            }
        }
    }
    
}

 

posted @ 2018-12-01 11:41  Maskisland  阅读(140)  评论(0编辑  收藏  举报