1.环形链表
public class Solution {
public boolean hasCycle ( ListNode head) {
if ( head == null || head. next == null) return false ;
ListNode fast = head. next;
ListNode slow = head;
while ( fast != slow) {
if ( fast. next == null || fast. next. next == null) return false ;
fast = fast. next. next;
slow = slow. next;
}
return true ;
}
}
2.最小栈
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。 push(x) —— 将元素 x 推入栈中。 pop() —— 删除栈顶的元素。 top() —— 获取栈顶元素。 getMin() —— 检索栈中的最小元素。
class MinStack {
private Stack< Integer> stack;
public MinStack ( ) {
stack = new Stack < Integer> ( ) ;
}
public void push ( int x) {
if ( stack. isEmpty ( ) ) {
stack. push ( x) ;
stack. push ( x) ;
} else {
int tmp = stack. peek ( ) ;
stack. push ( x) ;
if ( tmp< x) {
stack. push ( tmp) ;
} else {
stack. push ( x) ;
}
}
}
public void pop ( ) {
stack. pop ( ) ;
stack. pop ( ) ;
}
public int top ( ) {
return stack. get ( stack. size ( ) - 2 ) ;
}
public int getMin ( ) {
return stack. peek ( ) ;
}
}
3.相交链表
public class Solution {
public ListNode getIntersectionNode ( ListNode headA, ListNode headB) {
if ( headA == null || headB == null) return null;
ListNode pA = headA, pB = headB;
while ( pA != pB) {
pA = pA == null ? headB : pA. next;
pB = pB == null ? headA : pB. next;
}
return pA;
}
}
4.多数元素
多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。 输入:[2,2,1,1,1,2,2] 输出:2
class Solution {
public int majorityElement ( int [ ] nums) {
int count = 0 , last = 0 ;
for ( int num: nums) {
if ( count == 0 ) {
last = num;
}
count = count + ( last == num? 1 : - 1 ) ;
}
return last;
}
}
5.反转链表
class Solution {
ListNode pre = null;
public ListNode reverseList ( ListNode head) {
if ( head== null || head. next== null) return head;
ListNode p = reverseList ( head. next) ;
head. next. next = head;
head. next = null;
return p;
}
}