Learn the basics of Python-data structures, algorithms, design patterns---one-way lists

Source: Internet
Author: User
Tags prev



It seems that the following is the most elegant implementation.



Other, either node redundancy, or initialize ugly ...


 
#!/usr/bin/env python
# -*- coding: utf-8 -*-


class Node:
    
  def __init__(self, initdata):
    self.__data = initdata
    self.__next = None
    
  def getData(self):
    return self.__data

  def getNext(self):
    return self.__next

  def setData(self, newdata):
    self.__data = newdata
    
  def setNext(self, newnext):
    self.__next = newnext

    
class SinCycLinkedlist:
    
  def __init__(self):
    self.head = Node(None)
    self.head.setNext(self.head)
    
  def add(self, item):
    temp = Node(item)
    temp.setNext(self.head.getNext())
    self.head.setNext(temp)
    
  def remove(self, item):
    prev = self.head
    while prev.getNext() != self.head:
      cur = prev.getNext()
      if cur.getData() == item:
        prev.setNext(cur.getNext())
      prev = prev.getNext()
      
  def search(self, item):
      
    cur = self.head.getNext()
    while cur != self.head:
      if cur.getData() == item:
        return True
      cur = cur.getNext()
    return False

  def empty(self):
    return self.head.getNext() == self.head
  def size(self):
    count = 0
    cur = self.head.getNext()
    while cur != self.head:
      count += 1
      cur = cur.getNext()
    return count

if __name__ == ‘__main__‘:
  s = SinCycLinkedlist()
  print(‘s.empty() == %s, s.size() == %s‘ % (s.empty(), s.size()))
  s.add(19)
  s.add(86)
  print(‘s.empty() == %s, s.size() == %s‘ % (s.empty(), s.size()))
  print(‘86 is%s in s‘ % (‘‘ if s.search(86) else ‘ not‘,))
  print(‘4 is%s in s‘ % (‘‘ if s.search(4) else ‘ not‘,))
  print(‘s.empty() == %s, s.size() == %s‘ % (s.empty(), s.size()))
  s.remove(19)
  print(‘s.empty() == %s, s.size() == %s‘ % (s.empty(), s.size()))





Learn the basics of Python-data structures, algorithms, design patterns---one-way lists


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.