今日学习的文章链接和视频链接
203.移除链表元素
● 自己看到题目的第一想法
根据链表的性质,分情况讨论,
头节点一种情况,非头节点一种情况。
● 看完代码随想录之后的想法
利用虚拟头节点,将以上两种情况合二为一,
简化了代码量,非常tricky。
● 自己实现过程中遇到哪些困难
这题耗时较短比较顺利
● 今日收获
复习了链表基本原理和性质,
了解了链表与数组间的不同以及他俩各自的使用场景
// 普通解法
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode cur = head;
while(cur != null && cur.next != null){
if(cur.next.val == val){
cur.next = cur.next.next;
}else {
cur = cur.next;
}
}
// delete head
if(head != null && head.val == val) {
head = head.next;
}
return head;
}
}
// 虚拟表头
class Solution {
public ListNode removeElements(ListNode head, int val) {
// set dummy head
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode cur = dummyHead;
while(cur.next != null){
if(cur.next.val == val){
cur.next = cur.next.next;
}else {
cur = cur.next;
}
}
head = dummyHead.next;
return head;
}
}
707.设计链表
● 自己看到题目的第一想法
首先需要先定义好节点,然后再根据链表的具体性质依次实现各个功能。
● 看完代码随想录之后的想法
和我的想法契合
● 自己实现过程中遇到哪些困难
本来想使用虚拟头节点解决删除节点以及添加节点的问题,
后面发现这样会使index增加从而导致定位不准确,产生错误。
● 今日收获
明天补完双链表实现再写
//单链表
public class Listnode {
int val;
Listnode next;
Listnode() {}
Listnode(int val) {this.val = val;}
}
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 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) {
Listnode pre = head;
Listnode newNode = new Listnode(val);
if (index > size || index < 0) {
return;
}
for(int i = 0; i < index; i++){
pre = pre.next;
}
Listnode tmp = pre.next;
pre.next = newNode;
newNode.next = tmp;
size++;
}
public void deleteAtIndex(int index) {
Listnode pre = head;
if(index < 0 || index >= size) return;
if(index == 0) head = head.next;
for(int i = 0; i < index; i++){
pre = pre.next;
}
pre.next = pre.next.next;
size--;
}
}
// TODO 双链表
206.反转链表
● 自己看到题目的第一想法
使用双指针将各个节点逐个反转。
● 看完代码随想录之后的想法
不仅可以用双指针还可以用递归算法。
● 自己实现过程中遇到哪些困难
递归算法实现耗时较久,终止条件纠结了很久。
● 今日收获
重新复习了一边递归算法
//双指针法
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while(cur != null){
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}
//递归法
class Solution {
public ListNode reverseList(ListNode head) {
return reverseHelper(null,head);
}
public ListNode reverseHelper(ListNode pre, ListNode cur){
if(cur == null){
return pre;
}
ListNode tmp = cur.next;
cur.next = pre;
return reverseHelper(cur, tmp);
}
}
// TODO 从后往前递归