使用python建立简单的单链表

代码

import sys


class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


# 将列表转换成链表
def list_to_listnode(numbers):
    dummy_root = ListNode(0)
    ptr = dummy_root
    for number in numbers:
        ptr.next = ListNode(number)
        ptr = ptr.next
    ptr = dummy_root.next
    return ptr


# 遍历链表
def travel_listnode(head):
    res = head
    while res is not None:
        print(res.val)
        res = res.next


def main():
    line = sys.stdin.readline().strip()
    values = list(map(int, line.split()))
    head = list_to_listnode(values)
    travel_listnode(head)


if __name__ == '__main__':
    main()

输入输出

input:
21 34 45 656 

output:
21
34
45
656

练习

LeetCode19. Remove Nth Node From End of List 删除链表中的倒数第n个位置的元素

你可能感兴趣的:(python,算法与数据结构,数据结构_python实现)