面试题6:从尾到头打印链表

首先学习python的list: 

  list和tuple采用了顺序表的实现技术,两者主要的区别在tuple是不变的表,不支持改变其内部状态的任何操作,其他方法,两者类似。
  list是元素个数可变的顺序表,可以加入和删除元素。

  插入元素:list.insert(位置,元素),list.append(元素)

  清除元素:list.clear()   list.remove(list[])   del list[]

  倒序:list.reverse()

  排序:list.sort()  时间复杂度为O(nlog(n))

链表的基本知识

1 class lNode:
2     def __init__(self,elem,next_=None):
3         self.elem = elem   #元素
4         self.next_ = next_  #指向下个元素的地址(指针,索引)

加入元素:

 1 #表首端加入元素,若加入新元素为13
 2 q = LNode(13)
 3 q.next = head.next  #将原来的head.next赋值给新元素的地址
 4 head = q                 #直接将q赋值为head
 5 
 6 
 7 #一般情况的元素插入:
 8 q = LNode(13)
 9 q.next = pre.next
10 pre.next = q

删除元素:

1 #删除表首元素
2 head = head.next
3 
4 
5 
6 #删除中间元素
7 
8 pre.next = pre.next.next

 

 对应的题目:

 书上给的思路: 把这个问题当作栈处理,用栈来实现这个函数。

 

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        if not listNode:
            return []
        
        result = [] 
        while listNode:
            result.insert(0,listNode.val)
            listNode = listNode.next
        return result

  

posted @ 2019-07-19 20:09  lililili——  阅读(229)  评论(0)    收藏  举报