示例#1
0

class Solution:
    def findKthToLast(self, head, k):
        def findSize(head):
            size = 0
            while head is not None:
                size += 1
                head = head.next
            return size

        n = findSize(head)
        ctr = 0
        while head is not None:
            if (ctr == n - k):
                return head.val
            ctr += 1
            head = head.next

        return None


if __name__ == '__main__':
    ls = LinkedList()
    for i in [1, 3, 5, 2, 4, 2, 3, 5, 6]:
        node = Node(i)
        ls.addNode(node)
    s = Solution()
    k = int(input("Enter the value of K -\n"))
    ans = s.findKthToLast(ls.head, k)
    print("{} element from the last is {}".format(k, ans))
示例#2
0
import types
from typing import List
import collections
from slist import SList

from node import Node
from linkedList import LinkedList


def pairNodeSwap(node: Node):

    cur = node

    while cur.val and cur.next.val:
        cur.val, cur.next.val = cur.next.val, cur.val
        cur = cur.next.next

    return cur


myList = LinkedList()
myList.addNode(5)
myList.addNode(7)
myList.addNode(8)
myList.addNode(9)

myList.printNode()
示例#3
0
    final = Node(1) if start.val >= 10 else Node(0)
    start.val = start.val % 10 if start.val >= 10 else start.val
    answer = final
    while start is not None and start.next is not None:
        if start.next.val >= 10:
            start.val += 1
            start.next.val = start.next.val % 10
        final.next = start
        final = final.next
        start = start.next

    return answer.next if answer.val == 0 else answer


if __name__ == '__main__':
    ls1 = LinkedList()
    ls2 = LinkedList()
    for i in [9, 9, 7, 1, 6]:
        node = Node(i)
        ls1.addNode(node)
    for i in [9, 9, 5]:
        node = Node(i)
        ls2.addNode(node)

    #res = sumReverseOrder(ls1.head, ls2.head)
    res = sumForwardOrder(ls1, ls2)
    while res:
        print(str(res.val) + " -> ", end="")
        res = res.next

    print("None\n")