二叉树反转
/*public class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode root;
}*/
public class Solution{
public TreeNode invertTree(TreeNode root){
if(root == null) return null;
if(root.left != null) return invertTree(root.left);
if(root.right != null) return invertTree(root.right);
TreeNode temp=root.left;
root.left=root.right;
root.right=temp;
return root;
}
}
链表反转
非递归算法
public class reverse{
public static ListNode reverseList(ListNode phead){
ListNode pReverseHead=null;
ListNode pNode=phead;
ListNode pPrev=null;
while(pNode!=null){
ListNode pNext=pNode.next;
if(pNext==null) { pReverseHead = pNode ; }
pNode.next=pPrev;
pPrev=pNode;
pNode=pNext;
}
return pReverseHead;
}
}
递归算法
public class reverse{
public static reverseList(ListNode head){
if(head==null || head.next==null) return head;
ListNode nNext=head.next;//存储next
head.next=null;//将next全部断开
ListNode pPrev=reverseList(nNext);
nNext.next=head;//接上之前的节点
return pPrev;
}
}
利用栈
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
ArrayList<Integer> arraylist=new ArrayList<Integer>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
Stack<Integer> stack=new Stack<Integer>();
while(listNode!=null){
stack.push(listNode.val);
listNode=listNode.next;
}
ArrayList<Integer> list=new ArrayList<Integer>();
while(!stack.isEmpty()){
list.add(stack.pop());
}
return list;
}
}
数组反转
解法一
public class reverse{
public static void reverseList(int []arr){
for(int i=0;i<arr.length/2;i++){
int temp=arr[i];
a[i] = arr[arr.length-i-1];
arr[arr.length-i-1]=temp;
}
}
}
解法二
public class reverse{
public static void reverseList(int []arr){
for(int start=0,end=arr.length-1;start<end;start++,end--){
int temp=arr[start];
a[start] = arr[end];
arr[end]=temp;
}
}
}
解法三
public class reverse{
public static int[] reverseList(int []arr){
int []newarr = new int [arr.length];
for(int i=arr.length-1,j=0 ; i>0; i++,j++ ){
newarr[j]=arr[i];
}
return newarr;
}
}