链表相关:[https://www.cnblogs.com/tojian/p/10055036.html]
二叉树相关:[https://www.jianshu.com/p/0190985635eb ]
二叉树中序遍历[https://blog.csdn.net/qq_41231926/article/details/82056504]
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if pHead == None:
return None
if pHead.next == None:
return pHead
left = pHead
mid = pHead.next
right = mid.next
left.next = None
while right != None:
mid.next = left # mid.next之前已经有值了,所以这边应该是重新被赋值。
left = mid
mid = right
right = right.next # right 只是一个string变量
mid.next = left
return mid
反转.PNG
单链表.png
反转链表.PNG
链接:[https://www.nowcoder.com/questionTerminal/75e878df47f24fdc9dc3e400ec6058ca](https://www.nowcoder.com/questionTerminal/75e878df47f24fdc9dc3e400ec6058ca)
来源:牛客网
public ListNode ReverseList(ListNode head) {
if (head == null)
return null;
//head为当前节点,如果当前节点为空的话,那就什么也不做,直接返回null;
ListNode pre = null;
ListNode next = null;
//当前节点是head,pre为当前节点的前一节点,next为当前节点的下一节点
//需要pre和next的目的是让当前节点从pre->head->next1->next2变成pre<-head next1->next2
//即pre让head节点可以反转所指方向,但反转之后如果不用next节点保存next1节点的话,此单链表就此断开了
//所以需要用到pre和next两个节点
//1->2->3->4->5
//1<-2<-3 4->5
while (head != null) {
//做循环,如果当前节点不为空的话,始终执行此循环,此循环的目的就是让当前节点从指向next到指向pre
//如此就可以做到反转链表的效果
//先用next保存head的下一个节点的信息,保证单链表不会因为失去head节点的原next节点而就此断裂
next = head.next;
//保存完next,就可以让head从指向next变成指向pre了,代码如下
head.next = pre;
//head指向pre后,就继续依次反转下一个节点
//让pre,head,next依次向后移动一个节点,继续下一次的指针反转
pre = head;
head = next;
}
//如果head为null的时候,pre就为最后一个节点了,但是链表已经反转完毕,pre就是反转后链表的第一个节点
//直接输出pre就是我们想要得到的反转后的链表
return pre;
}
中序遍历
public ArrayList<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
ArrayList<Integer> res = new ArrayList<Integer>();
TreeNode node = root;
while (!stack.isEmpty() || node != null) {
while (node != null) {
stack.push(node);
node = node.left;
}
node = stack.pop();
res.add(node.val);
node = node.right;
}
return res;
}
https://www.nowcoder.com/questionTerminal/75e878df47f24fdc9dc3e400ec6058ca
https://www.nowcoder.com/questionTerminal/75e878df47f24fdc9dc3e400ec6058ca
https://v.qq.com/x/page/v07272pk0af.html?
(17条消息) 常见面试算法题汇总(Android面试)_Bestyou's Blog-CSDN博客_android 算法面试
剑指 offer 笔记 15 | 反转链表 - 简书 (jianshu.com)