祝福你有前路坦途的好运,更祝愿你能保持内心光亮
纵有风雨,依然选择勇敢前行
—— 24.9.22
203. 移除链表元素
给你一个链表的头节点
head
和一个整数val
,请你删除链表中所有满足Node.val == val
的节点,并返回 新的头节点 。示例 1:
输入:head = [1,2,6,3,4,5,6], val = 6 输出:[1,2,3,4,5]示例 2:
输入:head = [], val = 1 输出:[]示例 3:
输入:head = [7,7,7,7], val = 7 输出:[]提示:
- 列表中的节点数目在范围
[0, 104]
内1 <= Node.val <= 50
0 <= val <= 50
方法1
思路
定义哨兵节点,定义两个指针,指针1指向头结点,指针2指向头结点的下一个结点,进行循环,比较指针2指向的结点是否等于要删除的结点,如果等于,则接着后移进行遍历,直至指针2指向空,遍历结束
/**
* 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 static ListNode removeElements(ListNode head, int val) {
ListNode s = new ListNode(-1,head);
ListNode p1 = s;
ListNode p2 = s.next;
while (p2 != null) {
if (p2.val == val) {
p1.next = p2.next;
p2 = p2.next;
}else {
p1 = p2;
p2 = p2.next;
}
}
return s.next;
}
}
方法2
思路
递归函数负责返回:从当前节点开始,完成删除的的链表
1.若当前节点与目标相等,应该返回下一个节点递归结果
2.若当前节点与目标不等,应该返回当前节点,但当前节点的 next 应该更新
/**
* 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) {
if (head == null) {
return head;
}
head.next = removeElements(head.next, val);
return head.val == val ? head.next : head;
}
}
完整代码
ListNode类定义
package Day9ListPractice;
public class ListNode {
public int val;
public ListNode next;
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
// 可变长参数
public static ListNode of(int...numbers) {
ListNode head = new ListNode(0, null);
ListNode current = head;
for (int number : numbers) {
current.next = new ListNode(number, null);
current = current.next;
}
return head;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(64);
sb.append("[");
ListNode p = this;
while (p != null) {
sb.append(p.val);
if (p.next != null) {
sb.append(",");
}
p = p.next;
}
sb.append("]");
return sb.toString();
}
}
方法函数
public class LeetCode203RemoveListData {
// 方法1 迭代
public static ListNode removeElements1(ListNode head, int val) {
ListNode s = new ListNode(-1,head);
ListNode p1 = s;
ListNode p2 = s.next;
while (p2 != null) {
if (p2.val == val) {
p1.next = p2.next;
p2 = p2.next;
}else {
p1 = p2;
p2 = p2.next;
}
}
return s.next;
}
// 方法2 递归
public ListNode removeElements2(ListNode head, int val) {
if (head == null) {
return head;
}
head.next = removeElements2(head.next, val);
return head.val == val ? head.next : head;
}
public static void main(String[] args) {
ListNode head = ListNode.of(1,2,3,4,5,6,7,8);
System.out.println(head);
System.out.println(new LeetCode203RemoveListData().removeElements1(head, 1));
System.out.println(new LeetCode203RemoveListData().removeElements2(head, 7));
}
}