**给你一个链表的头节点 **head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
示例 1:
1 2
输入:head = [1,2,6,3,4,5,6], val = 6 输出:[1,2,3,4,5]
示例 2:
1 2
输入:head = [], val = 1 输出:[]
示例 3:
1 2
输入:head = [7,7,7,7], val = 7 输出:[]
** **提示:
**列表中的节点数目在范围 **[0, 104] 内
1 <= Node.val <= 50
0 <= val <= 50
题解:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: dummy = ListNode(0) dummy.next = head current = dummy #创建了虚拟头结点 while current and current.next: if current.next.val==val: current.next=current.next.next else : current=current.next return dummy.next
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head or not head.next: return head odd = head even = head.next even_head = even # 保存偶数链的起点 while even and even.next: odd.next = even.next odd = odd.next even.next = odd.next even = even.next # 连接奇数链尾部到偶数链头 odd.next = even_head return head
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def isPalindrome(self, head: Optional[ListNode]) -> bool: # 特殊情况:空链表或只有一个节点,必然是回文 if not head or not head.next: return True dummy=ListNode(0) dummy.next=head left,right=dummy,dummy while right and right.next: right=right.next.next left=left.next current=head second_half_list = [] while left.next: second_half_list.append(left.next.val) left = left.next while second_half_list: if current.val != second_half_list.pop(): return False current = current.next return True