半夜睡不着爬起来把今天任务完成了
之前链表就有搞虚拟节点,比较懵的是反转链表;其他俩个还行。
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; }
}
// 给你一个链表的头节点 head 和一个整数 val ,
// 请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点
public ListNode removeElements(ListNode head, int val) {
if (head == null) return null;
ListNode dummp = new ListNode(-1);
dummp.next = head;
ListNode p = dummp;
while ( p.next != null ){
if (p.next.val == val){
p.next = p.next.next;
}else {
p = p.next;
}
}
return dummp.next;
}
class MyLinkedList {
int size;
ListNode head;
public MyLinkedList() {
size = 0;
head = new ListNode(0);
}
public int get(int index) {
if (index < 0 || index > size) return -1;
ListNode curr = head;
for (int i = 0; i < index; i++) {
curr = curr.next;
}
return curr.val;
}
public void addAtHead(int val) {
ListNode newNode = new ListNode(val);
newNode.next = head;
}
public void addAtTail(int val) {
ListNode newNode = new ListNode(val);
ListNode curr = head;
while (curr != null){
curr = curr.next;
}
curr.next = newNode;
}
public void addAtIndex(int index, int val) {
if (index < 0 || index > size) return ;
ListNode curr = head;
ListNode newNode = new ListNode(val);
for (int i = index; i > 0; i--) {
curr = curr.next;
}
ListNode tmp = curr.next;
curr.next = newNode;
newNode.next = tmp;
}
public void deleteAtIndex(int index) {
if (index < 0 || index > size) return ;
ListNode curr = head;
for (int i = index; i > 0; i--) {
curr = curr.next;
}
curr.next = curr.next.next;
}
}
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null){
return head;
}
ListNode last = reverseList(head.next);
head.next.next = head;
head.next = null;
return last;
}
}
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}