19. 删除链表的倒数第 N 个结点

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode cur = head;
ListNode pre = null;
while(cur!=null){
n--;
if(n==-1){
pre=head;
}
if(n<-1){
pre=pre.next;
}
cur=cur.next;
}
if (n>0){
return head;
}
if(pre==null){
return head.next;
}
pre.next=pre.next.next;
return head;
}
}
20. 有效的括号

import java.util.*;
class Solution {
public boolean isValid(String s) {
//1.创建一个栈用来存储左括号
Stack<String> chars = new Stack<>();
//2.从左往右遍历字符串,拿到每一个字符
for (int i = 0; i < s.length(); i++) {
String currChar = s.charAt(i) + "";
//3.判断该字符是不是左括号,如果是,放入栈中存储
if (currChar.equals("(")|| currChar.equals("{") || currChar.equals("[")) {
chars.push(currChar);
} else if (currChar.equals(")") || currChar.equals("}") || currChar.equals("]")) {
//4.判断该字符是不是右括号,如果不是,继续下一次循 环 //5.如果该字符是右括号,则从栈中弹出一个元素t;
if(chars.isEmpty()){
return false;
}
String t = chars.pop();
if((t.equals("(" ) && currChar.equals(")")) || (t.equals("[") && currChar.equals("]")) || (t.equals("{") && currChar.equals("}"))){
}else {
return false;
}
}
}
//7.循环结束后,判断栈中还有没有剩余的左括号,如果有,则不匹配,如果没有,则匹配
if (chars.size() == 0) {
return true;
} else {
return false;
}
}
}
21. 合并两个有序链表

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 == null ) return list2;
if (list2 == null ) return list1;
ListNode head = list1.val >= list2.val ? list2 : list1;
ListNode cur1 = head.next;
ListNode cur2 = head == list1 ? list2 : list1;
ListNode pre = head;
while (cur2 != null && cur1 != null) {
if (cur1.val >= cur2.val) {
pre.next = cur2;
cur2 = cur2.next;
} else {
pre.next = cur1;
cur1 = cur1.next;
}
pre = pre.next;
}
pre.next = cur1 != null ? cur1 : cur2;
return head;
}
}