删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
为链表添加虚拟头节点
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode removeElements(ListNode head, int val) {
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode pre = dummyHead;
while(pre.next != null){
if(pre.next.val == val){
ListNode delNode = pre.next;
pre.next = delNode.next;
delNode.next = null;
} else {
pre = pre.next;
}
}
return dummyHead.next;
}
private String printListNode(ListNode head) {
StringBuilder res = new StringBuilder();
res.append("head [");
ListNode cur = head;
while(cur != null){
res.append(cur.val).append(",");
cur = cur.next;
}
res.deleteCharAt(res.length() - 1);
res.append("] tail");
return res.toString();
}
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeElements(self, head, val):
dummyHead = ListNode(-1)
dummyHead.next = head
pre = dummyHead
while(pre.next != None):
if(pre.next.val == val):
delNode = pre.next
pre.next = delNode.next
delNode.next = None
else:
pre = pre.next
return dummyHead.next
def printListNode(self, head):
res = "head ["
cur = head
while(cur != None):
res += str(cur.val) + ","
cur = cur.next
res = res[:-1]
res += "] tail"
return res