Example #1
0
def swapPairs(head):
    dummy = cur = Node(0)
    cur.next = head

    while cur.next and cur.next.next:  # 从head 和 head的下一个 开始
        p1 = cur.next
        p2 = cur.next.next

        p1.next = p2.next  # p1 在 p2 前变化
        p2.next = p1
        cur.next = p2

        # cur.next = p2
        # p1.next = p2.next
        # p2.next = p1

        cur = cur.next.next
    return dummy.next


lst = LinkedList()
lst.add_last(1)
lst.add_last(2)
lst.add_last(3)
lst.add_last(4)
lst.printlist()
lst.head.next = swapPairs(lst.head.next)
lst.printlist()
lst.head.next = swapPairs(lst.head.next)
lst.printlist()
Example #2
0
            node = node.next
    return head

# 删除所有重复的,一个不留 Given 1->1->1->2->3, return 2->3.
def deleteDuplicates2(head):
    dummy = pre = Node(0) # dummy 留着作为开头连接后面,   pre去连接后面的
    dummy.next = head # dummy和LL连接起来

    while head and head.next:
        if head.value == head.next.value:
            while head and head.next and head.value == head.next.value:
                head = head.next
            head = head.next
            pre.next = head
        else:
            pre = pre.next
            head = head.next
    return dummy.next


lst = LinkedList()
lst.add_last(1)
lst.add_last(3)
lst.add_last(3)
lst.add_last(3)
lst.add_last(5)
lst.add_last(7)
lst.add_last(7)
lst.add_last(9)
lst.head.next = deleteDuplicates2(lst.head.next)
lst.printlist()
# -*- coding:utf-8 -*-
"""
author: lijingxin

Created on 12:35 PM 4/25/20

"""
from util.LinkedList import LinkedList
from util.LinkedList import Node
def isPalindrome(head):
    rev = None
    slow = fast = head
    while fast and fast.next:
        fast = fast.next.next
        rev, rev.next, slow = slow, rev, slow.next
    if fast:
        slow = slow.next
    while rev and rev.value == slow.value: # 满足条件  slow往后移一个, rev往前移一个
        slow = slow.next
        rev = rev.next
    return not rev

lst = LinkedList()
lst.add_last(1)
lst.add_last(3)
lst.add_last(5)
lst.add_last(7)
lst.add_last(9)
lst.printlist()
print(isPalindrome(lst.head.next))
lst.printlist()