题目
请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。
现有一个链表 -- head = [4,5,1,9],它可以表示为:
4 -> 5 -> 1 -> 9
示例 1:
输入: head = [4,5,1,9], node = 5 输出: [4,1,9] 解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
示例 2:
输入: head = [4,5,1,9], node = 1 输出: [4,5,9] 解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
说明:
- 链表至少包含两个节点。
- 链表中所有节点的值都是唯一的。
- 给定的节点为非末尾节点并且一定是链表中的一个有效节点。
- 不要从你的函数中返回任何结果。
python代码实现:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next
注:
链表的初始化操作:
class Node:
def __init__(self, x):
self.val = x
self.next = None
class Solution():
def __init__(self,node):
self.head=Node(node)
self.head.next=None
def add(self, node):
node.next=self.head.next
self.head.next=node
def removeNthFromEnd(self,head,n):
new_head = Node(0)
new_head.next = head
fast = slow = new_head
for i in range(n + 1):
fast = fast.next
while fast:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return new_head.next
def isPalindrome(self, head):
if head == None or head.next == None:
return True
#利用快慢指针法寻找链表的中点
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# slow = slow.next
slow = self.reverseList(slow)
#前半段与后半段进行对比
while slow:
if head.val != slow.val:
return False
slow = slow.next
head = head.next
return True
#利用头插法反转后半段链表
def reverseList(self, head):
new_head = None
while head:
p = head
head = head.next
p.next = new_head
new_head = p
return new_head
def hasCycle(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
def main():
node2 = Node(1)
node3 = Node(2)
node4 = Node(3)
node5 = Node(4)
node6 = Node(5)
node7 = Node(6)
node8 = Node(7)
linklist = Solution(0)
linklist2 = Solution(0)
linklist.add(node2)
linklist.add(node3)
linklist.add(node4)
linklist.add(node6)
linklist.add(node8)
linklist2.add(node2)
linklist2.add(node3)
linklist2.add(node5)
# i=1
# while linklist.head is not None:
# # i = +1
# # print(i)
# linklist.head=linklist.head.next
# linklist.print_list()
t=Solution(1)
# nu=t.mergeTwoLists(linklist.head,linklist2.head)
nu = t.isPalindrome(linklist.head)
# while nu is not None:
# # i = +1
# # print(i)
# print(nu.val)
# nu=nu.next
print(nu)
if __name__ == '__main__':
main()