Sword finger Offer 24. Reverse the linked list

Define a function that takes the head node of a linked list, reverses the list, and outputs the head node of the reversed list.

Example:

Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL

Limitations:

0 <= Number of nodes <= 5000

Answer:

java

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode p = head;
        ListNode q = null;
        while(p! =null){ ListNode t = p.next; p.next = q; q = p; p = t; }returnq; }}Copy the code

python

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        p = head
        q = None
        while p:
            t = p.next
            p.next = q
            q = p
            p = t
        return q
Copy the code

25. Merge two sorted lists

Enter two incrementally sorted lists and merge them so that the nodes in the new list are still incrementally sorted.

Example 1:

Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4

0 <= List length <= 1000

21) leetcode-cn.com/problems/me…

51,372 passes and 69,326 submissions



java

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; }} * * /
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode res = new ListNode(0);
        ListNode p = res;
        while(l1! =null && l2! =null){if(l1.val<=l2.val){
                res.next = l1;
                l1 = l1.next;
                
            }
            else{
                res.next = l2;
                l2 = l2.next;
               
            }
            res = res.next;
        }
        if(l1==null && l2! =null){ res.next = l2; }if(l1! =null && l2==null){ res.next = l1; }returnp.next; }}Copy the code

python

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        p = ListNode(0)
        res = p
        while l1 and l2:
            if l1.val <= l2.val:
                res.next = l1
                l1 = l1.next
            else:
                res.next = l2
                l2 = l2.next
            res = res.next
        if not l1:
            res.next = l2
        else:
            res.next = l1
        return p.next
Copy the code

Offer 27. Mirror of binary tree

Complete a function that inputs a binary tree and outputs its mirror image.

Example 1:

Input: root = [4,2,7,1,3,6,9]

java

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; }} * * /
class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root==null) return null;
        TreeNode tmp = mirrorTree(root.left);
        root.left = mirrorTree(root.right);
        root.right = tmp;
        returnroot; }}Copy the code

python

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution(object):
    def mirrorTree(self, root):
        """ :type root: TreeNode :rtype: TreeNode """
        if not root:
            return 
        tmp = root.left
        root.left = self.mirrorTree(root.right)
        root.right = self.mirrorTree(tmp)
        return root
Copy the code

28. Symmetric binary tree

Implement a function to determine whether a binary tree is symmetric. A binary tree is symmetric if it is the same as its mirror image.



java

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; }} * * /
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root==null){
            return true;
        }else{
            returnisS(root.left,root.right); }}boolean isS(TreeNode L,TreeNode R){
            if(L==null && R==null){
                return true;
            }
            if(L==null || R==null || L.val! =R.val){return false;
            }
            returnisS(L.left,R.right) && isS(L.right,R.left); }}Copy the code

python

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution(object):
    
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def isS(L,R):
            if not L and not R:
                return True
            if not L or not R or L.val!=R.val:
                return False
            return isS(L.left,R.right) and isS(L.right,R.left)

        if not root :
            return True
        return isS(root.left,root.right)
    
Copy the code

Finger Offer 29. Print matrix clockwise

Enter a matrix and print out each number in clockwise order from the outside in.

Example 1:

Input: matrix = [[1, 2, 3], [4 and 6], [7,8,9]] output:,2,3,6,9,8,7,4,5 [1] example 2:

Input: matrix = [[1, 2, 3, 4], [5,6,7,8], [9,10,11,12]] output:,2,3,4,8,12,11,10,9,5,6,7 [1]

Limitations:

0 <= matrix.length <= 100

0 <= matrix[i].length <= 100

java

class Solution {
    public int[] spiralOrder(int[][] matrix) {
        if(matrix.length == 0) return new int[0];
        int r = matrix[0].length - 1 ;
        int low = matrix.length - 1;
        int l = 0;
        int top = 0;
        int x = 0;
        int[] res = new int[(r + 1) * (low + 1)];

        while(true) {for(inti=l; i<=r; i++){ res[x++] = matrix[top][i]; } top++;if(top>low) break;
            for(inti = top; i<=low; i++){ res[x++] = matrix[i][r]; } r--;if(l>r) break;
            for(inti = r; i>=l; i--){ res[x++] = matrix[low][i]; } low--;if(top>low) break;
            for(inti = low; i>=top; i--){ res[x++] = matrix[i][l]; } l++;if(l>r) break;


        }
        returnres; }}Copy the code

python

class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int] "" "if not matrix:
            return []
        l = 0
        r = len(matrix[0])- 1
        top = 0
        low = len(matrix)- 1
        res = []
        while True:
            for i in range(l,r+1):
                res.append(matrix[top][i])
            top = top+1
            if top>low: 
                break
            for i in range(top,low+1):
                res.append(matrix[i][r])
            r = r - 1
            if r<l: 
                break
            for i in range(r,l- 1.- 1):
                res.append(matrix[low][i])
            low = low - 1 
            if low < top: 
                 break
            for i in range(low,top- 1.- 1):
                res.append(matrix[i][l])
            l = l + 1
            if l>r: 
                break
        return res
Copy the code

Refer to Offer 30. Stack containing min function

Define the data structure of the stack. Please implement a min function in this type that can get the smallest element of the stack. In this stack, the time complexity of calling min, push and pop is O(1).

Example:

MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.min(); –> return -3.minstack.pop (); minStack.top(); –> return 0. Minstack.min (); — — > to return to 2.

Tip:

The total number of calls for each function does not exceed 20000 times

Answer:

Define two queues or stacks. When pushing into A, determine whether it can push into B as well. When pushing out of the queue, if A enters and exits the same as the last one of B, then B also exits

java

class MinStack {
    Stack<Integer> A, B;
    /** initialize your data structure here. */
    public MinStack(a) {
        A = new Stack<>();
        B = new Stack<>();
    }
    
    public void push(int x) {
        A.add(x);
        if(B.empty() || B.peek() >= x){ B.add(x); }}public void pop(a) {
        if(A.pop().equals(B.peek())){ B.pop(); }}public int top(a) {
        return A.peek();
    }
    
    public int min(a) {
        returnB.peek(); }}/** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.min(); * /
Copy the code

python

class MinStack(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.A = []
        self.B = []


    def push(self, x):
        """ :type x: int :rtype: None """
        self.A.append(x)
        if not  self.B or self.B[- 1]>=x:
            self.B.append(x)


    def pop(self):
        """ :rtype: None """
        if self.A.pop() == self.B[- 1]:
            self.B.pop()


    def top(self):
        """ :rtype: int """
        return self.A[- 1]

    def min(self):
        """ :rtype: int """
        return self.B[- 1]



# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.min()
Copy the code