Java review common data structures and common interview questions

preface

Tip: if you don't study hard, autumn moves and spring moves are your brother

Tip: the following is the text of this article, which comes from the geek time series tutorials. The following cases are for reference

1. Array and Linked List

Array: in memory, an array is a contiguous area
Linked List: Linked List can exist anywhere in memory and does not require continuity.

Array feature (array)

1. Fast reading

2. Insert and delete slow


Due to the continuous memory of Array, inserting and deleting often need to move back one by one, unless you insert the last position.

Time complexity

Array
• Access: O(1)
• Insert: average O(n)
• Delete: average O(n)

Linked List features (Linked List)

Single linked list memory model


Each node saves the memory address of the next data, and finds the next data through this address.

It can be seen that the search of this data structure needs to be addressed node by node, and the efficiency is relatively low

Insert and delete

Insert operation

First, make the pointer field of the next node of the new node point to the original tail, and then hang it to the node to be inserted

Delete operation

Directly skip the node to be deleted and point to the next node

Time complexity

Time complexity
space       O(n)
prepend 	O(1)
append      O(1)
lookup      O(n)
insert      O(1)
delete      O(1)

Summary of characteristics

ArrayLinked List
readO(1)O(n)
insertO(n)O(1)
deleteO(n)O(1)

Respective advantages and disadvantages

Advantages of arrays:

  • Strong random access
  • Fast search speed

Disadvantages of arrays

  • Inefficient insertion and deletion
  • May waste memory
  • Memory space requirements are high, and there must be enough continuous memory space.
  • The array size is fixed and cannot be expanded dynamically

Advantages of linked list

  • Fast insertion and deletion
  • Memory utilization is high and memory will not be wasted
  • The size is not fixed, and the expansion is very flexible.

Disadvantages of linked list

  • It cannot be searched randomly, and must be traversed from the first one, which is inefficient

Practical topic

  1. Reverse linked list: https://leetcode.com/problems/reverse-linked-list/
  2. Switch the nodes in the linked list in pairs: https://leetcode.com/problems/swap-nodes-in-pairs
  3. https://leetcode.com/problems/linked-list-cycle
  4. https://leetcode.com/problems/linked-list-cycle-ii
  5. https://leetcode.com/problems/reverse-nodes-in-k-group/

Personal problem solving ideas

Custom ListNode

package LinkedList;

public class ListNode {
   //Data domain
   public int val;

   //Next node domain
   public ListNode next;

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

1. Reverse linked list

Iterative thinking

Recursive thinking

package com.gdpu.day1;

import LinkedList.ListNode;

/**
 * Reverse linked list
 * https://leetcode.com/problems/reverse-linked-list/
 *
 */

public class NO_206_ReverseLinkedList {

    //iterative method 
    public ListNode reverseList(ListNode head){
        //Front pointer
        ListNode prev =null;
        //Current pointer
        ListNode curr = head;
        //When the last pointer is not reached
        while (curr!=null){
            //Reverse the operation of a
            ListNode next = curr.next;
            curr.next = prev;
            //Move backward
            prev =curr;
            curr =next;
        }
        return prev;
    }

    //Recursive solution
    public ListNode recursive(ListNode head){
        //Recursive termination condition
        //head is null, or it has reached the last node, exit
        if (head ==null ||head.next==null){
            return head;
        }
        ListNode p = recursive(head.next);
        //A ring points back to the front
        head.next.next = head;
        //Set the current next to null
        head.next =null;
        return p;
    }
}

2. Exchange the nodes in the linked list in pairs

Recursive thinking

Take advantage of the first in and last out characteristics of the stack

package com.gdpu.day1;

import LinkedList.ListNode;

import java.util.Stack;

public class NO_24_swapPairs {

    /**
     * Recursive exit: if the current node or the next node is empty, return
     * Method content: the current node next, points to the current node, and the pointers are interchanged
     * Return value: returns the node where the exchange is completed
     */
    public ListNode swapPairsRecursive(ListNode head) {
        //Termination condition of recursion
        if(head==null || head.next==null) {
            return head;
        }
        //Suppose the linked list is 1 - > 2 - > 3 - > 4
        //Save node 2 first
        ListNode tmp = head.next;
        //Continue recursion and process nodes 3 - > 4
        //When the recursion ends and returns, it becomes 4 - > 3
        //So the head node points to 4 and becomes 1 - > 4 - > 3
        head.next = swapPairsRecursive(tmp.next);
        //Point 2 node to 1
        tmp.next = head;
        return tmp;
    }

    //Use stack
    public ListNode swapPairsByStack(ListNode head) {
        if(head==null || head.next==null) {
            return head;
        }
        //Save the two nodes of each iteration with stack
        Stack<ListNode> stack = new Stack<ListNode>();
        ListNode p = new ListNode(-1);
        ListNode cur = head;
        //Head points to the new p node. At the end of the function, just return head.next
        head = p;
        while(cur!=null && cur.next!=null) {
            //Put the two nodes into the stack
            stack.add(cur);
            stack.add(cur.next);
            //Two steps forward for the current node
            cur = cur.next.next;
            //Pop up two nodes from the stack, and then point to the two newly popped nodes with the p node
            p.next = stack.pop();
            p = p.next;
            p.next = stack.pop();
            p = p.next;
        }
        //Note the boundary condition. When the length of the linked list is odd, cur is not empty
        if(cur!=null) {
            p.next = cur;
        } else {
            p.next = null;
        }
        return head.next;
    }


}

Tags: Java data structure Interview

Posted on Fri, 10 Sep 2021 01:21:58 -0400 by trace