Leetcode 203.移除链表元素
题目链接
思路:移除链表中的元素,核心就是将指向该元素的指针指向要移除元素所指向的下一个元素
代码:
/**
* Definition for singly-linked list.
* 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; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
// 判断头节点是否为null
if (head == null) {
return head;
}
// 链表中移除头节点和移除其他节点的操作方式是不同的,所以这里为了统一操作方式,
// 在头节点的前面创建一个虚拟头节点,令其指向头节点
ListNode dummyHead = new ListNode(-1, head);
ListNode cur = dummyHead;
while (cur.next != null) {
if (cur.next.val == val) {
// 移除链表中元素的本质:就是将指向该元素的指针指向要移除元素指向的下一个元素
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
// 虚拟头节点的下一个节点即为头节点
return dummyHead.next;
}
}
Leetcode 707.设计链表
题目链接
思路:设计链表这道题是值得我们重视的,这里建议使用虚拟头节点去实现,以保证添加节点和删除节点操作的一致性(ps:若果不使用虚拟节点,添加和删除头节点和其他节点的操作存在差异),需要注意的是使用虚拟头节点之后,这个虚拟头节点就变成了链表的第0个位置,所以要注意index的变化。这道题既可以设计成单链表,也可以设计成双链表,我这里是使用了虚拟头节点设计的单链表。
代码:
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
}
class MyLinkedList {
int size;
// 使用虚拟头节点
ListNode dummyHead;
public MyLinkedList() {
size = 0;
dummyHead = new ListNode(-1);
}
public int get(int index) {
if (index < 0 || index >= size) {
return -1;
}
// 这里一定要注意,虚拟头节点是第0个位置,所以查找的index的下一个位置才是不包含虚拟头节点链表的index位置
ListNode cur = dummyHead;
for (int i = 0; i < index; i++) {
cur = cur.next;
}
return cur.next.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 = dummyHead;
for (int i = 0; i < index; i++) {
pre = pre.next;
}
ListNode node = new ListNode(val);
// 这里注意指向的顺序
node.next = pre.next;
pre.next = node;
size++;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size) {
return;
}
// 找到要删除节点的前驱
ListNode pre = dummyHead;
for (int i = 0; i < index; i++) {
pre = pre.next;
}
pre.next = pre.next.next;
size--;
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList obj = new MyLinkedList();
* int param_1 = obj.get(index);
* obj.addAtHead(val);
* obj.addAtTail(val);
* obj.addAtIndex(index,val);
* obj.deleteAtIndex(index);
*/
Leetcode 206.反转链表
题目链接
思路:直接上图(图片来源:代码随想录)
代码:
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode tmp = null;
while (cur != null) {
// tmp用来保存cur的next节点,否则cur的next指向pre后就找不到原本cur后面的节点了
tmp = cur.next;
// 反转指针的指向
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}