1. 如何判断一个链表有环
题目描述:
有一个单向链表,链表中有可能出现环,如下图所示,那么如何通过程序来判断该链表是否为有环链表呢?
代码:
package comic;
import charpter2.ListNode;
/**
* @author chengzhengda
* @version 1.0
* @date 2019-11-05 12:49
* @desc 判断一个链表是否有环
*/
public class t1 {
public static boolean hasCircle(ListNode head) {
if (head == null) {
return false;
}
ListNode p1 = head;
ListNode p2 = head;
while ((p2 != null && p1.next != null)) {
p1 = p1.next;
p2 = p2.next.next;
if (p1 == p2) {
return true;
}
}
return false;
}
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(5);
ListNode node6 = new ListNode(6);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = node6;
node6.next = node1;
System.out.println(hasCircle(node1));
}
}
2. 最小栈的实现
题目描述:
实现一个栈,该栈带有入栈、出栈、取最小元素3个方法。要保证这3个方法的时间复杂度都是O(1)。
代码:
package comic;
import java.util.Stack;
/**
* @author chengzhengda
* @version 1.0
* @date 2019-11-06 22:47
* @desc 实现一个拥有push, pop, getMin方法的栈
*/
public class t2 {
public Stack<Integer> stack1 = new Stack<Integer>();
public Stack<Integer> stack2 = new Stack<Integer>();
public void push(int num) {
stack1.push(num);
if (stack2.isEmpty()) {
stack2.push(num);
} else if (stack2.peek() >= num) {
stack2.push(num);
}
}
public int pop() {
int res;
if (stack1.isEmpty()) {
res = -1;
} else {
res = stack1.pop();
if (! stack2.isEmpty() && res == stack2.peek()) {
stack2.pop();
}
}
return res;
}
public int getMin() {
if (stack2.isEmpty()) {
return -1;
} else {
return stack2.peek();
}
}
public static void main(String[] args) {
t2 stack = new t2();
stack.push(7);
stack.push(3);
stack.push(5);
stack.push(4);
stack.push(3);
while (!stack.stack2.isEmpty()) {
System.out.println(stack.stack2.pop());
}
System.out.println(stack.getMin());
stack.pop();
System.out.println(stack.getMin());
stack.pop();
System.out.println(stack.getMin());
stack.pop();
System.out.println(stack.getMin());
}
}
3. 最大公约数
题目描述:
求出两个整数的最大公约数
代码:
package comic;
/**
* @author chengzhengda
* @version 1.0
* @date 2019-11-06 23:30
* @desc 求两个整数的最大公约数
*/
public class t3 {
public static int getBiggestCom(int a, int b) {
int max = a > b ? a : b;
int min = a < b ? a : b;
int remainder = max - min;
if (remainder == 0) {
return min;
} else {
return getBiggestCom(remainder, min);
}
}
public static void main(String []args)
{
System.out.println(getBiggestCom(40,8));
}
}
4. 如何判断一个数是否是2的整数次幂
代码:
package comic;
/**
* @author chengzhengda
* @version 1.0
* @date 2019-11-22 12:50
* @desc 判断一个整数是否为2的幂
*/
public class t4 {
public static boolean isPower(int num) {
return (num & (num - 1)) == 0;
}
public static void main(String[] args) {
System.out.println(isPower(16));
}
}