刷题日记03
203. 移除链表元素
比较基础的链表操作,对链表进行增删改的时候使用虚头节点会更方便操作。而遍历链表一般是不需要虚头节点的
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode pre = new ListNode(){};
pre.next = head;
ListNode cur = pre;
while(cur.next != null){
if(cur.next.val == val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return pre.next;
}
}
707. 设计链表
也是二刷这道题了,花了半小时勉强做出来,主要还是考察对虚节点的使用,一般定义一个pre节点操作就可以了,我这里定义了pre和cur两个节点,其实有点多余。
class MyLinkedList {
private int size;
private ListNode head;
public MyLinkedList() {
this.size = 0;
this.head = new ListNode(0);
}
public int get(int index) {
if(index >= size || index < 0) return -1;
ListNode cur = head;
for(int i = 0; i <= index; i++){
cur = cur.next;
}
return cur.val;
}
public void addAtHead(int val) {
addAtIndex(0, val);
}
public void addAtTail(int val) {
addAtIndex(size, val);
}
public void addAtIndex(int index, int val) {
if(index > size) return;
if(index < 0) index = 0;
ListNode pre = head;
ListNode newNode = new ListNode(val);
for(int i = 0; i < index; i++){
pre = pre.next;
}
newNode.next = pre.next;
pre.next = newNode;
size++;
}
public void deleteAtIndex(int index) {
if(index >= size || index < 0) return;
ListNode cur = head;
ListNode pre = new ListNode(0);
pre.next = head;
for(int i = 0; i <= index; i++){
cur = cur.next;
pre = pre.next;
}
pre.next = cur.next;
size--;
}
}
class ListNode {
int val;
ListNode next;
ListNode(){}
ListNode(int val){
this.val = val;
}
}
206. 反转链表
也是比较经典的题,需要两个指针pre和cur,再定义一个temp临时变量储存下一个节点,想清楚逻辑的话,算是比较简单的一道题。
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while(cur != null){
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}