How to input and output linked list in python

Generally, the input and output linked list takes an array as input 在这里插入代码片, and thenwrite a functionConvert to linked list.

  • Take deleting duplicate elements in the linked list as an example to write a code:
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class LinkList:
    def __init__(self):
        self.head = None

    def initList(self, data):
        # 创建头结点
        self.head = ListNode(data[0])
        r = self.head
        p = self.head
        # 逐个为 data 内的数据创建结点, 建立链表
        for i in data[1:]:
            node = ListNode(i)
            p.next = node
            p = p.next
        return r

    def printlist(self, head):
        if head == None: return
        node = head
        while node:
            print(node.val,end='')
            if node.next:
                print(',',end='')
            node = node.next

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if not head:
            return head
        cur = head
        while cur.next:
            if cur.val == cur.next.val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return head


if __name__ == '__main__':
    arr = input('')
    num = [int(n) for n in arr.split(',')]
    ans = Solution()
    l = LinkList()
    l1 = l.initList(num)
    l.printlist(ans.deleteDuplicates(l1))

Guess you like

Origin blog.csdn.net/toCVer/article/details/125721322