尋找list的中間元素

給定一個(gè)非環(huán)的單向鏈表,尋找該鏈表的中間元素

可以通過(guò)兩個(gè)指針同時(shí)遍歷的方式,一個(gè)前進(jìn)一步,一個(gè)前進(jìn)兩步,最后慢的指針?biāo)肝恢脼殒湵碇虚g元素

# coding: utf-8
# @author zhenzong
# @date 2018-05-20 13:24


class Node(object):

    def __init__(self, value, next_node):
        self.value = value
        self.next_node = next_node

    def __str__(self):
        return str(self.value)

    __repr__ = __str__


def mid_list(head):
    if not head:
        return None
    slow, fast = head, head
    while fast.next_node and fast.next_node.next_node:
        fast = fast.next_node.next_node
        slow = slow.next_node
    return slow


def list_to_str(_node):
    if not _node:
        return ''
    ret = str(_node)
    tmp = _node.next_node
    while tmp:
        ret = '%s,%s' % (ret, tmp)
        tmp = tmp.next_node
    return ret


def test(length_array):
    for length in length_array:
        node = None
        for i in range(length, 0, -1):
            node = Node(i, node)
        print 'length: %s, list: %s, mid: %s' % (length, list_to_str(node), mid_list(node))


test([1, 2, 3, 10, 11, 12])

# 輸出
# length: 1, list: 1, mid: 1
# length: 2, list: 1,2, mid: 1
# length: 3, list: 1,2,3, mid: 2
# length: 10, list: 1,2,3,4,5,6,7,8,9,10, mid: 5
# length: 11, list: 1,2,3,4,5,6,7,8,9,10,11, mid: 6
# length: 12, list: 1,2,3,4,5,6,7,8,9,10,11,12, mid: 6
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容