我报名参加金石计划1期挑战——瓜分10万奖池,这是我的第n篇文章,点击查看活动详情
一、前言
今天是代码训练营第三天,链表相关,LeetCode题分别是 206. 反转链表 707. 设计链表 203. 移除链表元素
二、 206. 反转链表
题目描述
思路分析
这个比较简单, 搞个新链表,一个中间节点然后来回切换就可以了
代码展示
class Solution {
public ListNode reverseList(ListNode head) {
ListNode result = null;
ListNode cur = head;
ListNode temp = null;
while(cur != null){
temp = cur.next;
cur.next = result;
result = cur;
cur = temp;
}
return result;
}
}
提交结果
三、 707. 设计链表
题目描述
思路分析
在这道题上面卡了很久,之前刷的时候落下了这道题,只有一点思路做起来就很难
其中添加首尾节点的方法都可以使用指定下标添加方法复用来做
主要需要注意的就是理解每个方法的作用,同时计算好边界
代码展示
public class MyLinkedList {
int size;
ListNode node;
public MyLinkedList() {
size = 0;
node = new ListNode(0);
}
public int get(int index) {
if (index < 0 || index >= size){
return -1;
}
ListNode root = node;
for (int i = 0; i <= index; i++) {
root = root.next;
}
return root.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 temp = node;
for (int i = 0; i < index; i++) {
temp = temp.next;
}
ListNode root = new ListNode(val);
root.next = temp.next;
temp.next = root;
size++;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size){
return;
}
size--;
if(index == 0){
node = node.next;
return;
}
ListNode temp = node;
for (int i = 0; i < index; i++) {
temp = temp.next;
}
temp.next = temp.next.next;
}
@Override
public String toString() {
return "MyLinkedList{" +
"size=" + size +
", node=" + node +
'}';
}
}
提交结果
四、 203. 移除链表元素
题目描述
思路分析
也是使用中间节点来做的
代码展示
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null){
return null;
}
ListNode temp = new ListNode(-1, head);
ListNode pre = temp;
ListNode cur = head;
while(cur != null){
if (cur.val == val){
pre.next = cur.next;
}else{
pre = cur;
}
cur = cur.next;
}
return temp.next;
}
}
提交结果
五、总结
今天有点累,思路分析都有点简略,有代码看起来比较难的可以去看代码随想录的网站或者直接评论留言,每天摸鱼的我肯定可以非常及时的回复
本文内容到此结束了
如有收获欢迎点赞👍收藏💖关注✔️,您的鼓励是我最大的动力。
如有错误❌疑问💬欢迎各位大佬指出。
我是 宁轩 , 我们下次再见