@TOC
题目描述
题目1(24. 两两交换链表中的节点)
题目2(94. 二叉树的中序遍历)
解题思路
题目1(24. 两两交换链表中的节点)
遍历链表,每次交换head.next和head.next.next节点,直到d.next或head.next.next为空。
题目2(94. 二叉树的中序遍历)
二叉树的遍历可以参考:https://blog.csdn.net/weixin_43598687/article/details/119514459
代码实现
题目1(24. 两两交换链表中的节点)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
//当链表为空或只有一个节点时直接返回
if(head == null || head.next ==null) return head;
ListNode newNode = new ListNode(0,head);
ListNode temp = newNode;
while(temp.next != null && temp.next.next != null){
ListNode node1 = temp.next;
ListNode node2 = temp.next.next;
temp.next = node2;
node1.next = node2.next;
node2.next = node1;
temp = node1;
}
return newNode.next;
}
}
题目2(94. 二叉树的中序遍历)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
while (root != null || !stack.empty()) {
if (root != null) {
stack.push(root);
root = root.left;
}else{
root = stack.pop();
res.add(root.val);
root = root.right;
}
}
return res;
}
}