leetcode刷题笔记 二百零三题 移除链表元素
源地址:203. 移除链表元素
问题描述:
删除链表中等于给定值 *val* 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4->5
//建立哨兵节点,从head节点开始遍历,遇到value值节点跳过
/**
* Definition for singly-linked list.
* class ListNode(_x: Int = 0, _next: ListNode = null) {
* var next: ListNode = _next
* var x: Int = _x
* }
*/
object Solution {
def removeElements(head: ListNode, value: Int): ListNode = {
var prev = new ListNode(-99)
var start = prev
var cur = head
prev.next = head
while(cur != null){
if (cur.x == value){
cur = cur.next
prev.next = cur
}
else{
cur = cur.next
prev = prev.next
}
}
return start.next
}
}