😊 大家好,我是作家桑。这是自己的一个 C# 做题记录,方便自己学习的同时分享出来。
注意,笔者使用的编译环境是 .NET 7 和 C# 11。
题目描述:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例:
输入:head = [1,3,2]
输出:[2,3,1]
代码实现:
/*** Definition for singly-linked list.* public class ListNode {* public int val;* public ListNode next;* public ListNode(int x) { val = x; }* }*/public class Solution
{List tmp = new List();int count = 0; // 用于计算链表中的节点个数 public int[] ReversePrint(ListNode head){reversal(head);int[] res = new int[count];for (int i = 0; i < res.Length; i++){res[i] = tmp[i];}return res;}public void reversal(ListNode head) {// 递归 if (head == null) return;reversal(head.next);tmp.Add(head.val);count++;}
}
运行结果:
思路讲解:
代码实现2:
/*** Definition for singly-linked list.* public class ListNode {* public int val;* public ListNode next;* public ListNode(int x) { val = x; }* }*/public class Solution {public int[] ReversePrint(ListNode head) {List myList = new List();while (head != null){myList.Add(head.val);head = head.next;}myList.Reverse();return myList.ToArray();}
}
运行结果2:
思路讲解:
题目描述:
输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
示例:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
代码实现:
public class TreeNode
{public int val;public TreeNode left;public TreeNode right;public TreeNode(int x) { val = x; }
}public class Solution
{public TreeNode BuildTree(int[] preorder, int[] inorder){int n = preorder.Length;if (n == 0) return null;if (n == 1) return new TreeNode(preorder[0]);TreeNode root = new TreeNode(preorder[0]); // 树节点 int index = Array.IndexOf(inorder, root.val);root.left = BuildTree(preorder[1..(index + 1)], inorder[..index]); // 左子树root.right = BuildTree(preorder[(index + 1)..], inorder[(index+1)..]); // 右子树return root; }
}
运行结果:
思路讲解:
题目描述:
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例:
输入:
[“CQueue”,“appendTail”,“deleteHead”,“deleteHead”,“deleteHead”]
[[],[3],[],[],[]]
输出:[null,null,3,-1,-1]
代码实现:
public class CQueue
{Stack inStack;Stack outStack; public CQueue(){inStack = new Stack();outStack = new Stack();}public void AppendTail(int value){inStack.Push(value);}public int DeleteHead(){if(outStack.Count == 0){if(inStack.Count == 0) // 没有元素可以删除了 return -1; while (inStack.Count > 0) // 把inStack栈内的所有元素放到outStack栈内outStack.Push(inStack.Pop());}return outStack.Pop();}
}
运行结果:
思路讲解:
🌻 以上就是本次的做题记录啦,希望大家看完有所收获。