目录
- class ListNode:
- def __init__(self, val = 0, next = None):
- self.val = val
- self.next = next
- # 在第i个位置插入elem
- def Inster(head, i, elem):
- assert i >= 0
- cur = head
- while i != 0:
- i -= 1
- cur = cur.next
- if not cur:
- return False
- temp = cur.next
- cur.next = elem
- elem.next = temp
- return True
- def ListDelete(head, i):
- assert i >= 0
- cur = head
- while i >= 0:
- i -= 1
- cur = cur.next
- if not cur.next:
- return False
- cur.next = cur.next.next
- return True
- def BulidLink_Head(l):
- head = ListNode()
- temp = head
- for elem in l:
- temp.next = ListNode(elem)
- temp = temp.next
- return head
-
- head = BulidLink_Tail([1,2,3,4])
- while head.next:
- head = head.next
- print(head.val)
- def BulidLink_Head(l):
- head = ListNode()
- temp = head
- for elem in l:
- temp = head.next
- head.next = ListNode(elem, temp)
- return head
解决单链表无法逆向索引的问题
- class DLinkNode:
- def __init__(self, val = 0, next = Node, prior):
- self.val = val
- self.next = next
- self.prior = prior
从一个结点出发可以找到其他任何结点
从头找到尾和从尾找到头的时间复杂度都是O(1)
一个链表的头节点head和一个整数val,请删除链表中所有满足Node.val == val的节点,并返回新的头节点。
- class solution:
- def removeElements(self, head, val):
- head = ListNode(next = head)
- pre = head
- while pre.next:
- if pre.next.val == val:
- pre.next = pre.next.next
- else:
- pre = pre.next
- return head.next
一个链表的头节点head ,旋转链表;将链表每个节点向右移动k个位置。
- class solution:
- def rotateRight(self, head, k):
- if not head:
- return None
- length = 0
- temp = head
- while temp.next:
- length += 1
- temp = temp.next
- temp.next = head
- k = k % (length + 1)
- temp = head
- for i in range(length - k):
- temp = temp.next
- head = temp.next
- temp.next = None
- return head