[3] offer prove safety. Print head from the end of the list [by Python]

    <div id="post_detail">
<div class="post">
	<h2>
		<a id="cb_post_title_url" href="https://www.cnblogs.com/huanjing/p/8763439.html">剑指offer试题——从尾到头打印链表</a>
	</h2>
	<div class="postText"><div id="cnblogs_post_body" class="blogpost-body"><p>输入一个链表,从尾到头打印链表每个节点的值。</p>
Copy the code
'' ' - Examinations defined classes - node ' '' 
# class ListNode: 
#      DEF the __init __ (Self, X): 
#          self.val = X 
#          self.next = None

class Solution:
# return a list of values from the sequence of the tail to the head, for example, [l, 2,3]
DEF printListFromTailToHead (Self, listnode):
# Write code here Wallpaper
L = []
head
= listnode
the while head:
l.insert (0 , head.val)
# 0 is the index value of each cycle head.val inserted at an index of 0, it is conceivable, while head cycle begins listnode
# the first node, the first node on a an index of 0, and then in the second node of an index of 0,
# when the value of the value field of the last node in the index positions 0, l obtained at this time is the first element value of the last node of the
head = head.next
return L

Copy the code

Knowledge points:

List: http: //zhaochj.github.io/2016/05/12/2016-05-12-%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84-% E9% 93% BE% E8% A1% A8 /

Written in a very good blog, very comprehensive, the following supplementary notes and do some reading this blog post, the original blog is a must see.

 

Advantage of the array

 

  • Random access and strong
  • Find Fast

 

An array of shortcomings

 

  • Low insertion and deletion efficiency
  • Memory may be wasted
  • Memory space requirements high, there must be enough contiguous memory space.
  • The array size is fixed and can not be dynamically expand

 

The list of advantages

 

  • Insert delete speed
  • High memory utilization, memory is not wasted
  • There is no fixed size, expanding very flexible.

 

The shortcomings of the list

 

  • Can not look random, we must begin traversed from the first, low search efficiency
- Array List
Reading O (1) O (n) inserting O (n) O (1) Remove O (n) O (1)

Chain is achieved between the logical data sequentially holding, storage space but not necessarily sequential approach. It can be used to represent a data structure of FIG This list of:

List
                Figure 1: list

The basic elements of the list:

  1. Nodes (or elements may also be called a node), each node has two domains, called the left part 值域, for storing user data; the right call 指针域, typically stored pointer to the next element
  2. head node, nodule is a special head, head node always points to the first node
  3. tail node, tail node is a special node, tail node always points to the last node
  4. None, pointer list the last node pointer field points to a value of None, because also known 接地点, so some of the information symbol on the electrically grounding the representative None

List of commonly used methods:

  1. LinkedList () creates an empty list, no arguments, the return value is an empty list
  2. is_empty () to test whether the list is empty, no parameters, return value is a Boolean value
  3. append (data) at the tail end of the list as an element to increase a. Parameters to append elements, no return value
  4. ITER () traverse the list, no parameters and returns no value, this method is generally a generator
  5. insert (idx, value) is inserted into an element, and the parameter index value into element
  6. remove (idx) removing an element, the element or index parameter to remove, and modify the list
  7. () Returns the number of elements in the list size, no arguments, return value is an integer
  8. search (item) to find a list element, the element parameter or index you are looking for, the return is a Boolean value

Node Class

python with the class data structure to implement linked list node (Node) are basic modules linked list implementation, each node includes at least two important parts. First of all, including the node's own data, referred to as "data field" (also known as range). Secondly, each node includes a "reference" next node (also called pointer)

Code for implementing a lower class Node:

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

 

This function constructs a node class is only receiving one data parameter, which nextrepresents a pointer to a domain, to obtain a node instantiated object, as follows:

node = Node (4)

 

This node object data 4, pointer to None.

Such a node object may be described with a more vivid illustration, as follows:

List
              Figure 2: Node

Objectlist

First look at building function LinkedList class:

class LinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

 


Examples of such a list is generated after the object, initialized headand tailthe node, and the node point to two None, instantiation code as follows:

    
link_list = LinkedList()

The list also indicates that the object with the map image, as follows:

List
                   Figure 3: empty list

 

note:

1. The node is the basic elements of the list, each node has a pointer field and range, each node may store more than one data, each node can be stored in an array

2. The two inputs to distinguish the following cases, different outputs

First define node

class ListNode:
    def __init__(self, x):
        selfval = the x
        self.next = None

Enables the printing head from the tail

Copy the code
class Solution:
     # return a list of values from the sequence of the tail to the head, for example, [l, 2,3] 
    DEF printListFromTailToHead (Self, listnode):
         # Write code here Wallpaper 
        L = []
        head = listNodewhile head:
            l.insert(0, head.val)
            head = head.next
        return l
Copy the code

Input:

a=Solution()
listnode=ListNode([1,2,3])
a.printListFromTailToHead(listnode)

Output:

[[1, 2, 3]]

看起来似乎并没有倒序打印,这是因为,我们这里定义的是一个节点,并没有形成链表,因此[1,2,3]是存在一个节点当中的,就这一个节点,倒序打印没有意义

节点的组成是数据域和指针域,而链表的组成是头,尾,单独来看,头,尾本身都是节点

下面看节点构成链表,对链表进行操作

先定义节点node,然后定义链表LinkList

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
Copy the code
class LinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
</span><span style="color: #0000ff;">def</span><span style="color: #000000;"> is_empty(self):
    </span><span style="color: #0000ff;">return</span> self.head <span style="color: #0000ff;">is</span><span style="color: #000000;"> None

</span><span style="color: #0000ff;">def</span><span style="color: #000000;"> append(self, data):
    node </span>=<span style="color: #000000;"> Node(data)
    </span><span style="color: #0000ff;">if</span> self.head <span style="color: #0000ff;">is</span><span style="color: #000000;"> None:
        self.head </span>=<span style="color: #000000;"> node
        self.tail </span>=<span style="color: #000000;"> node
    </span><span style="color: #0000ff;">else</span><span style="color: #000000;">:
        self.tail.next </span>=<span style="color: #000000;"> node
        self.tail </span>=<span style="color: #000000;"> node

</span><span style="color: #0000ff;">def</span><span style="color: #000000;"> iter(self):
    </span><span style="color: #0000ff;">if</span> <span style="color: #0000ff;">not</span><span style="color: #000000;"> self.head:
        </span><span style="color: #0000ff;">return</span><span style="color: #000000;">
    cur </span>=<span style="color: #000000;"> self.head
    </span><span style="color: #0000ff;">yield</span><span style="color: #000000;"> cur.data
    </span><span style="color: #0000ff;">while</span><span style="color: #000000;"> cur.next:
        cur </span>=<span style="color: #000000;"> cur.next
        </span><span style="color: #0000ff;">yield</span><span style="color: #000000;"> cur.data

</span><span style="color: #0000ff;">def</span><span style="color: #000000;"> insert(self, idx, value):
    cur </span>=<span style="color: #000000;"> self.head
    cur_idx </span>=<span style="color: #000000;"> 0
    </span><span style="color: #0000ff;">if</span> cur <span style="color: #0000ff;">is</span> None:             <span style="color: #008000;">#</span><span style="color: #008000;"> 判断是否是空链表</span>
        <span style="color: #0000ff;">raise</span> Exception(<span style="color: #800000;">'</span><span style="color: #800000;">The list is an empty list</span><span style="color: #800000;">'</span><span style="color: #000000;">)
    </span><span style="color: #0000ff;">while</span> cur_idx &lt; idx-1:   <span style="color: #008000;">#</span><span style="color: #008000;"> 遍历链表</span>
        cur =<span style="color: #000000;"> cur.next
        </span><span style="color: #0000ff;">if</span> cur <span style="color: #0000ff;">is</span> None:   <span style="color: #008000;">#</span><span style="color: #008000;"> 判断是不是最后一个元素</span>
            <span style="color: #0000ff;">raise</span> Exception(<span style="color: #800000;">'</span><span style="color: #800000;">list length less than index</span><span style="color: #800000;">'</span><span style="color: #000000;">)
        cur_idx </span>+= 1<span style="color: #000000;">
    node </span>=<span style="color: #000000;"> Node(value)
    node.next </span>=<span style="color: #000000;"> cur.next
    cur.next </span>=<span style="color: #000000;"> node
    </span><span style="color: #0000ff;">if</span> node.next <span style="color: #0000ff;">is</span><span style="color: #000000;"> None:
        self.tail </span>=<span style="color: #000000;"> node

</span><span style="color: #0000ff;">def</span><span style="color: #000000;"> remove(self, idx):
    cur </span>=<span style="color: #000000;"> self.head
    cur_idx </span>=<span style="color: #000000;"> 0
    </span><span style="color: #0000ff;">if</span> self.head <span style="color: #0000ff;">is</span> None:  <span style="color: #008000;">#</span><span style="color: #008000;"> 空链表时</span>
        <span style="color: #0000ff;">raise</span> Exception(<span style="color: #800000;">'</span><span style="color: #800000;">The list is an empty list</span><span style="color: #800000;">'</span><span style="color: #000000;">)
    </span><span style="color: #0000ff;">while</span> cur_idx &lt; idx-1<span style="color: #000000;">:
        cur </span>=<span style="color: #000000;"> cur.next
        </span><span style="color: #0000ff;">if</span> cur <span style="color: #0000ff;">is</span><span style="color: #000000;"> None:
            </span><span style="color: #0000ff;">raise</span> Exception(<span style="color: #800000;">'</span><span style="color: #800000;">list length less than index</span><span style="color: #800000;">'</span><span style="color: #000000;">)
        cur_idx </span>+= 1
    <span style="color: #0000ff;">if</span> idx == 0:   <span style="color: #008000;">#</span><span style="color: #008000;"> 当删除第一个节点时</span>
        self.head =<span style="color: #000000;"> cur.next
        cur </span>=<span style="color: #000000;"> cur.next
        </span><span style="color: #0000ff;">return</span>
    <span style="color: #0000ff;">if</span> self.head <span style="color: #0000ff;">is</span> self.tail:   <span style="color: #008000;">#</span><span style="color: #008000;"> 当只有一个节点的链表时</span>
        self.head =<span style="color: #000000;"> None
        self.tail </span>=<span style="color: #000000;"> None
        </span><span style="color: #0000ff;">return</span><span style="color: #000000;">
    cur.next </span>=<span style="color: #000000;"> cur.next.next
    </span><span style="color: #0000ff;">if</span> cur.next <span style="color: #0000ff;">is</span> None:  <span style="color: #008000;">#</span><span style="color: #008000;"> 当删除的节点是链表最后一个节点时</span>
        self.tail =<span style="color: #000000;"> cur

</span><span style="color: #0000ff;">def</span><span style="color: #000000;"> size(self):
    current </span>=<span style="color: #000000;"> self.head
    count </span>=<span style="color: #000000;"> 0
    </span><span style="color: #0000ff;">if</span> current <span style="color: #0000ff;">is</span><span style="color: #000000;"> None:
        </span><span style="color: #0000ff;">return</span> <span style="color: #800000;">'</span><span style="color: #800000;">The list is an empty list</span><span style="color: #800000;">'</span>
    <span style="color: #0000ff;">while</span> current <span style="color: #0000ff;">is</span> <span style="color: #0000ff;">not</span><span style="color: #000000;"> None:
        count </span>+= 1<span style="color: #000000;">
        current </span>=<span style="color: #000000;"> current.next
    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> count

</span><span style="color: #0000ff;">def</span><span style="color: #000000;"> search(self, item):
    current </span>=<span style="color: #000000;"> self.head
    found </span>=<span style="color: #000000;"> False
    </span><span style="color: #0000ff;">while</span> current <span style="color: #0000ff;">is</span> <span style="color: #0000ff;">not</span> None <span style="color: #0000ff;">and</span> <span style="color: #0000ff;">not</span><span style="color: #000000;"> found:
        </span><span style="color: #0000ff;">if</span> current.data ==<span style="color: #000000;"> item:
            found </span>=<span style="color: #000000;"> True
        </span><span style="color: #0000ff;">else</span><span style="color: #000000;">:
            current </span>=<span style="color: #000000;"> current.next
    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> found


Copy the code

输入:

link_list = LinkedList()
for i in range(150):
    link_list.append(i)

此时,link_list就是一个链表,链表的关键,head,tail

head,tail的本身就是一个节点,节点的两个基本组成数据域跟指针域,指针指向下一个节点的位置,这就是链表的不好之处,想要查找数据等只能遍历所有的节点

倒序打印

Copy the code
class Solution:
     # return a list of values from the sequence of the tail to the head, for example, [l, 2,3] 
    DEF printListFromTailToHead (Self, listnode):
         # Write code here Wallpaper 
        L = []
        link_list = listNode
        while link_list.head:
            l.insert(0, link_list.head.data)
            link_list.head=link_list.head.next
        return l
Copy the code

Input:

a=Solution()
a.printListFromTailToHead(link_list)

Output: seen at this time in reverse order Print

 

Guess you like

Origin blog.csdn.net/qq_33487726/article/details/90717625