题解 | #输出单向链表中倒数第k个结点#

输出单向链表中倒数第k个结点

http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d

虽然可以直接list,但是这是练习题,目的就是为了让自己发现自己缺点。我个人不推荐直接用list完成的。

class ListNode:
    def __init__(self):
        self.m_nKey = None
        self.m_pNext = None

class LN:
    def __init__(self):
        self.head = None
        self.tail = None
        
    def add(self, data):
        node = ListNode()
        node.m_nKey = data
        if self.head == None:
            self.head = node
            self.tail = node
        else:
            self.tail.m_pNext = node
            self.tail = node
    
    def printa(self):
        if self.head == self.tail:
                print(self.head.m_nKey, end=' ')
        else:
            p = self.head
            while p != None:
                print(p.m_nKey, end=' ')
                p = p.m_pNext
                
    def k_node(self, val):
        counter = 0
        temp = self.head
        for i in range(1,val):
            temp = temp.m_pNext
        return temp

while True:
    try:
        num = int(input())
        tmp = map(int,input().split())
        k = int(input())
        if k > num or k <= 0:
            print(0)
            continue
        nnd = LN()
        for i in tmp:
            nnd.add(i)
        not_rev = num - k + 1
        print(nnd.k_node(not_rev).m_nKey)
        
    except:
        break
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务