线性表

线性表:线性存储,链式存储

 

顺序存储:

  可以随机访问,通过给出的元素序号可以在O(1)时间内找到。

  删除和插入操作需要移动大量元素。O(n)

 

链式存储:

  不可以随机访问。访问需要O(n)。

  删除和插入操作O(n),但是找到相应元素需要O(n)

  创建链表:

    头插法:

    尾插法:

public LinkNode createHeadInsert(int arr[]){
        LinkNode head = new LinkNode();
        int i = 0;
        while(i < arr.length){
            LinkNode temp = new LinkNode(arr[i++]);
            LinkNode next = head.next;
            head.next = temp;
            temp.next = next;
        }
        return head.next;
    }
    public LinkNode createTailInsert(int arr[]){
        if (arr.length == 0){
            return null;
        }
        LinkNode head = new LinkNode();
        LinkNode p = head;
        int i = 0;
        while (i < arr.length){
            p.next = new LinkNode(arr[i++]);
            p = p.next;
        }
        return head.next;
    }

  插入删除:都需要找到要插入、删除的前一个节点。

public LinkNode insertByIndex(LinkNode list, int index, int val){
        LinkNode s = new LinkNode(val);
        if (index == 1){
            s.next = list;
            list = s;
        }else {
            LinkNode node = search(list, index - 1);
            if (node != null){
                s.next = node.next;
                node.next = s;
            }
        }
        return list;
    }

    public LinkNode removeByVal(LinkNode list, int val){
        if (list == null){
            return null;
        }
        if (list.val == val){
            return list.next;
        }
        LinkNode p = list.next;
        LinkNode pre = list;
        while (p != null && p.val != val){
            p = p.next;
            pre = pre.next;
        }
        pre.next = p.next;
        return list;
    }

 

  

  

posted @ 2020-05-21 10:48  lucy_cui  阅读(105)  评论(0)    收藏  举报