Chapter 2 Linked Lists - 2.2

来源:互联网 发布:女神联盟坐骑升阶数据 编辑:程序博客网 时间:2024/05/18 17:03
Problem 2.2: Implement an algorithm to find the nth to last element of a singly linked list.

The solution on answer page needs only one iteration while other intuitive solution takes more than one iteration.
def find_nth_to_last(head, n):    p1 = p2 = head    # Move p2 n nodes forward    for i in range(0, n):        # If p2 runs into the end of list,        # the input is invalid        if p2 == None:            return False        p2 = p2.next    # Move p2 and p1 together until    # p2 runs into the end of list    while True:        if p2 == None:            return p1        p2 = p2.next        p1 = p1.next
I learned that sometimes we can use more than one pointers to achieve a better solution.
原创粉丝点击