黄哥Python:单链表的尾部插入方法

213 阅读1分钟
原文链接: zhuanlan.zhihu.com

单链表的尾部插入方法:

1、先判断头结点是不是为None

2、设置一个当前结点node,循环下一个结点,当node.next 为None 时,就到尾部,也就是找到插入点了。

请看下面Python 代码。

#!/bin/python3

import math
import os
import random
import re
import sys

class SinglyLinkedListNode:
    def __init__(self, node_data):
        self.data = node_data
        self.next = None

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

def print_singly_linked_list(node, sep, fptr):
    while node:
        fptr.write(str(node.data))

        node = node.next

        if node:
            fptr.write(sep)

# Complete the insertNodeAtTail function below.

#
# For your reference:
#
# SinglyLinkedListNode:
#     int data
#     SinglyLinkedListNode next
#
#
def insertNodeAtTail(head, data):
    '''黄哥Python培训 黄哥所写'''
    if head is None:
        head = SinglyLinkedListNode(data)
        return head
    node = head
    while node.next is not None:
        node = node.next
    node.next = SinglyLinkedListNode(data)
    return head


if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    llist_count = int(input())

    llist = SinglyLinkedList()

    for i in range(llist_count):
        llist_item = int(input())
        llist_head = insertNodeAtTail(llist.head, llist_item)
        llist.head = llist_head

    print_singly_linked_list(llist.head, '\n', fptr)
    fptr.write('\n')

    fptr.close()


题目来自

Insert a Node at the Tail of a Linked List | HackerRankwww.hackerrank.com图标黄哥:黄哥Python:提醒要转行当程序员的朋友,学习要分先后主次zhuanlan.zhihu.com图标黄哥:黄哥Python培训是这样训练学员的zhuanlan.zhihu.com图标