题目链接:. - 力扣(LeetCode)
解题思路:虚拟头结点
根据题目可知,移除链表元素是不能改变原链表结构的,这就导致如果用上一篇博客旋转链表 (纯数学题)-优快云博客的数学思维可能会导致处理较为复杂,因此改变思路,直接操作链表。
其实不难发现,只要题目不要求维持原结构,大部分题目都可以转化为数学题,采用简单的数据结构先进行处理,然后再还原成所需要的数据结构。
话说回来,这道题比较重要的点就是临时指针的选定和临时指针下一个值与目标值是否相等的逻辑处理。看代码注释。
2024-7-21
/**
* 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) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode tmp = dummy;
while (tmp.next != null) {
// 如果临时指针下一个值与目标值相等,改变指向,而临时指针本身不变
if (tmp.next.val == val) {
tmp.next = tmp.next.next;
} else {
// 临时指针后移
tmp = tmp.next;
}
}
return dummy.next;
}
}
2024-08-09
/**
* 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) {
ListNode dummy = new ListNode(0);
dummy.next = head;
if (head == null) {
return head;
}
ListNode pre = dummy;
ListNode cur = pre.next;
while (cur != null) {
if (cur.val != val) {
// ListNode temp=cur.next;
pre = cur;
cur = cur.next;
} else {
ListNode temp = cur.next;
pre.next=temp;
cur=cur.next;
}
}
return dummy.next;
}
}