# class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None
class(object): defswapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if(head==None): return head trav1 = head trav2 = head.next if(trav2==None): return head head = head.next while(True): trav1.next = trav1.next.next trav2.next = trav1 if trav1.next == Noneor trav2.next==None: break trav2 = trav1.next if trav2.next == None: break trav1.next = trav2.next trav1 = trav2 trav2 = trav2.next return head
往右移动k个链表
1 2 3 4 5 6 7
Input: 0->1->2->NULL, k = 4 Output: 2->0->1->NULL Explanation: rotate 1 steps to the right: 2->0->1->NULL rotate 2 steps to the right: 1->2->0->NULL rotate 3 steps to the right: 0->1->2->NULL rotate 4 steps to the right: 2->0->1->NULL
# class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None
class(object): defrotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if head == None: returnNone cur = head length = 1 pos = 0 table = {} # count how many steps we need while cur and cur.next: cur = cur.next length += 1 steps = k % length n = 0 lastk = head while n < steps: lastk = lastk.next n+=1 last = head while lastk.next != None: lastk = lastk.next last = last.next lastk.next = head newhead = last.next last.next = None return newhead
# Definition for singly-linked list with a random pointer. # class RandomListNode(object): # def __init__(self, x): # self.label = x # self.next = None # self.random = None
class(object): defcopyRandomList(self, head): """ :type head: RandomListNode :rtype: RandomListNode """ map = {} iterNode = head while iterNode: map[iterNode] = RandomListNode(iterNode.label) iterNode = iterNode.next iterNode = head while iterNode: map[iterNode].next = map[iterNode.next] if iterNode.next elseNone map[iterNode].random = map[iterNode.random] if iterNode.random elseNone iterNode = iterNode.next return map[head] if head elseNone
近期评论