203. 移除链表元素
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
输入: head = [1,2,6,3,4,5,6], val = 6
输出: [1,2,3,4,5]
采用增加一个虚拟头节点解决问题
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummyHead = new ListNode();
dummyHead.next = head;
ListNode cur = dummyHead;
while(cur.next!= null){
if(cur.next.val == val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return dummyHead.next;
}
}
206. 反转链表
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
输入: head = [1,2,3,4,5]
输出: [5,4,3,2,1]
增加了头节点,本质上还是双指针法
class Solution {
public ListNode reverseList(ListNode head) {
ListNode dummy = null;
ListNode cur = head;
while(cur!=null){
ListNode temp = cur.next;
cur.next = dummy;
dummy = cur;
cur = temp;
}
return dummy;
}
}