Remove Linked List Elements (E)
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
题意
将给定链表中所有含有指定值的结点删除。
思路
注意需要连续删除结点的情况。
代码实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dumb = new ListNode(0);
dumb.next = head;
ListNode pre = dumb;
ListNode cur = head;
while (cur != null) {
if (cur.val == val) {
pre.next = cur.next;
cur = cur.next;
} else {
pre = pre.next;
cur = cur.next;
}
}
return dumb.next;
}
}
本文详细介绍了一种从链表中移除特定值元素的算法,通过创建哑节点简化操作,确保头节点不为要移除的元素。该算法遍历链表,当遇到目标值时,调整指针跳过该节点,直至链表末尾。
740

被折叠的 条评论
为什么被折叠?



