示例#1
0
            if count > k + 1:
                bp = bp.next
            q = p
            p = p.next
        if count <= 1:
            return head
        if count > k:
            outList = bp.next
            bp.next = None
            q.next = head
            return outList
        elif count == k:
            return head
        else:
            k = k % count
            if k == 0:
                return head
            p = head
            for i in range(count - k - 1):
                p = p.next
            outList = p.next
            p.next = None
            q.next = head
            return outList


if __name__ == '__main__':
    head = ListNode.initNodeList([1, 2])
    resList = Solution().rotateRight(head, 2)
    ListNode.linkListPrint(resList)
示例#2
0
from ListNode import ListNode

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if head is None or head.next is None:
            return head
        l1 = ListNode(0)
        l1.next = head
        pf,p,q = l1,head,head.next
        while p and q:
            p.next = q.next
            q.next = p
            pf.next = q
            pf = p
            p = p.next
            if p is None:
                break
            q = p.next
        return l1.next

if __name__ == '__main__':
    head = ListNode.initNodeList([1,2])
    head = Solution().swapPairs(head)
    ListNode.linkListPrint(head)
示例#3
0
from ListNode import ListNode


class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        if head is None:
            return head
        if head.next is None:
            return None
        p = head
        q = None
        count = 1
        while p.next != None:
            count += 1
            p = p.next
        p = head
        if count is n:
            return p.next
        for i in range(count - n):
            q = p
            p = p.next
        q.next = p.next
        return head


if __name__ == '__main__':
    arr = [1, 2]
    head = ListNode.initNodeList(arr)
    ListNode.linkListPrint(Solution().removeNthFromEnd(head, 2))