示例#1
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)
示例#2
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))