deflistToLinkedList(list_): '''将列表转换成链表''' linkhead = Node(list_[0]) p = linkhead # 逐个为列表内的数据创建结点, 建立链表 for i in list_[1:]: p.next = Node(i) p = p.next return linkhead # 链表头带着一串尾巴
defprintLinkedList1(head): '''打印链表1''' if head == None: returnFalse print(head.val) printLinkedList1(head.next)
defprintLinkedList2(node): '''打印链表2(按照字符串打印)''' ifnot node: return"[]" result = "" while node: result += str(node.val) + ", " node = node.next print("[" + result[:-2] + "]")
#################################################
l = listToLinkedList([1,2,3,6,3,4,5])
defdeleteNode(LinkedList, target): head = LinkedList p = head while p != None: if p.val == target: p.val, p.next = p.next.val, p.next.next else: p = p.next
deflistToLinkedList(list_): '''将列表转换成链表''' linkhead = Node(list_[0]) p = linkhead # 逐个为列表内的数据创建结点, 建立链表 for i in list_[1:]: p.next = Node(i) p = p.next return linkhead # 链表头带着一串尾巴
defprintLinkedList1(head): '''打印链表1''' if head == None: returnFalse print(head.val) printLinkedList1(head.next)
defprintLinkedList2(node): '''打印链表2(按照字符串打印)''' ifnot node: return"[]" result = "" while node: result += str(node.val) + ", " node = node.next print("[" + result[:-2] + "]")
#################################################
l = listToLinkedList([1,2,2,3])
defdeleteDuplicates(head): if head: before = head present = before.next while present: if present.val != before.val: before.next = present before = present else: before.next = None present = present.next return head
classNode: '''链表节点''' def__init__(self, x): self.val = x self.next = None
deflistToLinkedList(list_): '''将列表转换成链表''' linkhead = Node(list_[0]) p = linkhead # 逐个为列表内的数据创建结点, 建立链表 for i in list_[1:]: p.next = Node(i) p = p.next return linkhead # 链表头带着一串尾巴
defprintLinkedList1(head): '''打印链表1''' if head == None: returnFalse print(head.val) printLinkedList1(head.next)
defprintLinkedList2(node): '''打印链表2(按照字符串打印)''' ifnot node: return"[]" result = "" while node: result += str(node.val) + ", " node = node.next print("[" + result[:-2] + "]")
#################################################
l = listToLinkedList([1,2,3,4,5])
defreverseList(head): p, rev = head, None while p: rev, rev.next, p = p, rev, p.next return rev
deflistToLinkedList(list_): '''将列表转换成链表''' linkhead = Node(list_[0]) p = linkhead # 逐个为列表内的数据创建结点, 建立链表 for i in list_[1:]: p.next = Node(i) p = p.next return linkhead # 链表头带着一串尾巴
defprintLinkedList1(head): '''打印链表1''' if head == None: returnFalse print(head.val) printLinkedList1(head.next)
defprintLinkedList2(node): '''打印链表2(按照字符串打印)''' ifnot node: return"[]" result = "" while node: result += str(node.val) + ", " node = node.next print("[" + result[:-2] + "]")