1.判断链表是否有环
public boolean hasCycle(ListNode head){
if((head==null)||(head.next==null))
return false;
ListNode fast=head;
ListNode slow =head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow){
return true;
}
}
return false;
}
2.判断链表中的环的起始位置
public ListNode detecyle(ListNode head){
ListNode fast =head;
ListNode slow =head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow){
fast=head;
while(fast!=slow){
slow=slow.next;
fast=fast.next;
}
return slow;
}
}
return null;
}
3.反转链表
public ListNode reverse(ListNode head){
ListNode pre=null;
ListNode cur =head;
ListNode last=next;
while(cur!=null){
last=cur.next;
cur.next=pre;
pre=cur;
cur=last;
}
return pre;
}
4.合并两个单调递增的链表并输出。
public ListNode mergeList(ListNode l1,ListNode l2){
ListNode dummyHead=new ListNode(0);
ListNode cur=dummyHead;
while(l1!=null&&l2!=null){
if(l1.val<l2.val){
cur.next=l1;
cur=cur.next;
l1=l1.next;
}else{
cur.next=l2;
cur=cur.next;
l2=l2.next;
}
}
if(l1==null){
cur.next=l2;
}else{
cur.next=l1;
}
return dummyHead.next;
}
5.二叉树的各种遍历
5.1前序遍历(非递归)
public List<Integer> preOrderTraversal(TreeNode root){
Stack<Integer> stack =new Stack<Integer>();
List<Integer> traversal =new ArrayList<Integer>();
if(root!=null){
stack.add(root);
while(!stack.isEmpty()){
TreeNode cur=stack.pop();
traversal.add(cur.val);
if(cur.left!=null){
stack.add(cur.left);
}
if(cur.right!=null){
stack.add(cur.right);
}
}
return traversal;
}
}
5.2前序遍历(递归形式)
public class Soultion{
ArrayList<Integer> list =new ArrayList<Integer>();
public ArratList<Integer> preOrderTrav(TreeNode root){
if(root==null) return list;
list.add(root.val);
preOrderTrav(root.left);
preOrderTrav(root.right);
return list;
}
}
5.3二叉树的中序遍历(非递归形式)
public List<Integer> inOrderTrav(TreeNode root){
List<Integer> list =new ArrayList<Integer>();
Stack<Integer> stack =new Stack<Integer>();
TreeNode cur=root;
while(cur!=null||!stack.isEmpty()){
while(cur!=null){
stack.push(cur);
cur=cur.left;
}
cur= stack.pop();
list.add(cur.val);
cur=cur.right;
}
return list;
}
5.4中序遍历(递归形式)
public class Soultion{
ArrayList<Integer> list =new ArrayList<Integer>();
public ArrayList<Integer> inOrderTrav(TreeNode root){
if(root==null) return list;
inOrderTrav(root.left);
list.add(root.val);
inOrderTrav(root.right);
return list;
}
}
5.5后序遍历(非递归)
public List<Integer> postOrdTraver(TreeNode root){
LinkedList<Integer> ans =new LinkedList<Integer>();
Stack<Integer> stack =new Stack<Integer>();
if(root==null) return ans;
stack.push(root);
while(!stack.isEmpty()){
TreeNode cur =stack.pop();
ans.addFirst(cur.val);
if(cur.left!=null){
stack.push(cur.left);
}if(cur.right!=null){
stack.push(cur.right);
}
}
return ans;
}