从尾到头打印链表
# write code here
if not listNode:
return []
pHead = listNode
stack = []
while pHead:
stack.append(pHead.val)
pHead = pHead.next
return stack[::-1]
链表中倒数第k个结点
class Solution:
def FindKthToTail(self, head, k):
# write code here
if not head:
return None
pFast, pSlow = head, head
for i in range(k):
if pFast == None:
return None
pFast = pFast.next
while pFast:
pFast = pFast.next
pSlow = pSlow.next
return pSlow
反转链表
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if not pHead:
return None
pre = None
while pHead:
next_node = pHead.next # 提前存储当前节点的下一节点
pHead.next = pre # 翻转,当前节点的下一节点是其上一节点
pre = pHead # 上一节点向后移动
pHead = next_node # 当前节点向后移动
return pre
合并两个排序的链表
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
# write code here
if not pHead1:
return pHead2
if not pHead2:
return pHead1
mergeHead = None
if pHead1.val <= pHead2.val:
mergeHead = pHead1
mergeHead.next = self.Merge(pHead1.next, pHead2)
elif pHead1.val > pHead2.val:
mergeHead = pHead2
mergeHead.next = self.Merge(pHead1, pHead2.next)
return mergeHead
复杂链表的复制
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if pHead is None:
return None
# copy node set next
cur_node = pHead
while cur_node:
next_node = cur_node.next
copy_node = RandomListNode(cur_node.label)
cur_node.next = copy_node
copy_node.next = next_node
cur_node = next_node
# set random
cur_node = pHead
while cur_node:
next_node = cur_node.next
if cur_node.random is None:
next_node.random = None
else:
next_node.random = cur_node.random.next
cur_node = next_node.next
# split
new_head = pHead.next
cur_node = pHead
while cur_node:
next_node = cur_node.next
cur_node.next = next_node.next
if next_node.next is None:
next_node.next = None
else:
next_node.next = next_node.next.next
cur_node = cur_node.next
return new_head
两个链表的第一个公共结点
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
if not pHead1 or not pHead2:
return None
vals = []
while pHead1:
vals.append(pHead1.val)
pHead1 = pHead1.next
while pHead2:
if pHead2.val in vals:
return pHead2
pHead2 = pHead2.next
链表中环的入口结点
class Solution:
def EntryNodeOfLoop(self, pHead):
# write code here
if not pHead:
return null
nodes = []
cur_node = pHead
while cur_node:
if cur_node in nodes:
return cur_node
else:
nodes.append(cur_node)
cur_node = cur_node.next
删除链表中重复的结点
class Solution:
def deleteDuplication(self, pHead):
# write code here
if not pHead:
return None
preNode = ListNode(None)
preNode.next = pHead
last = preNode
cur = pHead
while cur and cur.next:
if cur.val == cur.next.val:
val = cur.val
while cur and cur.val == val:
cur = cur.next
last.next = cur
else:
last = cur
cur = cur.next
return preNode.next