203.移除链表元素
题目链接:力扣
重点了解了虚拟头结点的妙用。
解题代码:
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode();
dummy.next = head;
ListNode prev = dummy;
ListNode curr = head;
while (curr != null) {
if (curr.val == val) {
prev.next = curr.next;
} else {
prev = curr;
}
curr = curr.next;
}
return dummy.next;
}
707.设计链表
题目链接:力扣
设计连表让我对链表的理解更深,主要是自己慢慢的调试摸索出来的,下面放上我的代码。在写完自己的代码后,看了下代码随想录的代码,发现设置了大小和虚拟头节点,这两字段才是神来一笔,大大减轻了方法中的异常判断,我在设计的时候并没有想到,所以做了很多非空判断。代码随想录解析
解题代码:
class MyLinkedList {
private MyNode head;
class MyNode {
int val;
MyNode next;
}
public MyLinkedList() {
}
public int get(int index) {
MyNode indexNode = this.getNode(index);
int result = indexNode == null ? -1 : indexNode.val;
return result;
}
public MyNode getNode(int index) {
MyNode indexNode = null;
MyNode curr = head;
int i = 0;
while (curr != null) {
if (i == index) {
indexNode = curr;
break;
}
curr = curr.next;
i++;
}
return indexNode;
}
public void addAtHead(int val) {
if (this.head == null) {
this.head = new MyNode();
this.head.val = val;
} else {
MyNode newHead = new MyNode();
newHead.val = val;
newHead.next = this.head;
this.head = newHead;
}
}
public void addAtTail(int val) {
if (this.head == null) {
this.addAtHead(val);
} else {
MyNode last = this.head;
while (last.next != null) {
last = last.next;
}
MyNode newLast = new MyNode();
newLast.val = val;
last.next = newLast;
}
}
public void addAtIndex(int index, int val) {
if (index == 0) {
this.addAtHead(val);
return;
}
MyNode indexPreNode = this.getNode(index - 1);
if (indexPreNode == null) {
return;
}
MyNode newNode = new MyNode();
newNode.val = val;
newNode.next = indexPreNode.next;
indexPreNode.next = newNode;
}
public void deleteAtIndex(int index) {
if (index == 0) {
if (this.head != null) {
this.head = this.head.next;
}
return;
}
MyNode indexPreNode = this.getNode(index - 1);
if (indexPreNode == null) {
return;
}
if (indexPreNode.next != null) {
indexPreNode.next = indexPreNode.next.next;
}
}
}
206.反转链表
题目链接:力扣
熟练运用指针!这个题目在脑海或则电脑上还不好思考,双指针用纸笔画一下感觉更容易理顺。
解题代码:
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;
}
总结
链表的基础应该是了解了,设计链表时一开始有很多的冗余代码,写完后提交成功后,又慢慢的精简了一些,看完代码随想录的解析后,感觉有进了一步,明天有空再默写一遍。
现在每天花在算法上的时间有一点多了,需要给自己严格约束一些时间,想不到就立马看解析,理解记忆,晚上再按照理解进行默写,这样应该可以提升效率。