Ejemplo n.º 1
0
    # @return the head node in the linked list
   def rotateRight(self, A, B):
        length = self.getLength(A)
        if length == 1:
            return A
        B = B % length
        if B == 0:
            return A
        temp = A
        for _ in xrange(length-B-1):
            temp = temp.next
        head = temp.next
        temp.next = None
        temp = head
        while temp.next is not None:
            temp = temp.next
        temp.next = A
        return head
    
    def getLength(self, A):
        length = 0
        while A is not None:
            length += 1
            A = A.next
        return length

sol = Solution()
A = LinkedList.getRandomLinkedList(2)
LinkedList.printLinkedList(A)
A = sol.rotateRight(A, 2)
LinkedList.printLinkedList(A)
Ejemplo n.º 2
0
import pdb

class Solution:
    # @param A : head node of linked list
    # @return the head node in the linked list
    def swapPairs(self, A):
        start = LinkedList.ListNode("dummy")
        start.next = A
        current = start

        while current.next and current.next.next:
            current.next = self.swapNodes(current.next, current.next.next)
            current = current.next.next
        return start.next
    
    def swapNodes(self, A, B):
        A.next = B.next
        B.next = A
        return B

import LinkedList
A = LinkedList.getRandomLinkedList(11, 20)
LinkedList.printLinkedList(A)
sol= Solution()
B = sol.swapPairs(A)
LinkedList.printLinkedList(B)
Ejemplo n.º 3
0
        while B is not None:
            sum = B.val + carry
            carry = sum / 10
            C.next = ListNode(sum % 10)
            C = C.next
            B = B.next
        
        if carry != 0:
            C.next = ListNode(carry)

        return returnHead
    
    def reverseLinkedList(self, A):
        prev = None
        while A is not None:
            temp = A.next
            A.next = prev
            prev = A
            A = temp
        return prev


A = LinkedList.getRandomLinkedList(3)
B = LinkedList.getRandomLinkedList(5)
LinkedList.printLinkedList(A)
LinkedList.printLinkedList(B)

sol = Solution()
C = sol.addTwoNumbers(A,B)
LinkedList.printLinkedList(C)