203. 移除链表元素

随机pick的一道简单题
移除链表中的特定元素

我自己提交的代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
	def removeElements(self, head: ListNode, val: int) -> ListNode:
		***# 最开始忘记了head为空的情况***
		if head == None:
			return None
		while head.val == val:
			head = head.next
			if head == None:
				return None
		temp = head
		tail = head
		while tail != None:
			if tail.val != val:
				temp = tail
				tail = tail.next
			else:
				tail = tail.next
				temp.next = tail
		return head

然后提交通过以后
看题解才想起以前学数据结构好像有一个方法
是在head前面加一个虚拟的virtual_head,然后最后返回virtual_head.next
这样可以减去一开始对于head的处理
Mark一个范例:

在这里插入图片描述

Java实现移除链表元素有两种常见方法,分别是不使用虚拟节点和使用虚拟节点。 ### 不使用虚拟节点 不使用虚拟节点时,处理头结点需要进行判断。若要删除的元素是头结点,让`head = head.next`;若删除的不是头结点,让`head.next = head.next.next`即可删除元素。以下是具体代码: ```java class Solution { public ListNode removeElements(ListNode head, int val) { while (head!= null && head.val == val) { head = head.next; } // 将头结点赋值给cur,操作的是cur不要直接操作head节点。 ListNode cur = head; // 特别说明,这里定义cur要指向的是head,而不是head.next // 如果定义的cur = head.next的话,那么此时发现被删除的元素是head,这样就无法对head节点进行操作。 // 单链表是没有办法操作前一个元素 // 循环结束条件是链表为空 while (cur != null) { // 如果删除的元素的值与目标值相同 while (cur.next != null && cur.next.val == val) { // 将cur.next指向cur.next.next完成删除操作 cur.next = cur.next.next; } // 如果没有找到目标元素,cur向后移动 cur = cur.next; } return head; } } ``` ### 使用虚拟节点 使用虚拟节点会方便很多,但需要创建一个虚拟的头节点,并将其指向`head`。以下是具体代码: ```java /** * 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 dummyhead = new ListNode();// 需要创建:原因是目前没有 dummyhead.next = head; ListNode temp = dummyhead; if (head == null) { return null; } while (temp.next != null) { // 先要保证temp本身不是null if (temp.next.val == val) { temp.next = temp.next.next; } else { temp = temp.next; } } return dummyhead.next; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值