Linked List implemented by python

Source: Internet
Author: User

Python-implemented linked list, including insert, search, and delete operations

#! /Usr/bin/python class linknode (): def _ init _ (self, k, n = None): self. key = k; self. next = n; def createlist (): # create a linked list n = raw_input ("enter the num of nodes"); n = int (n); if n <1: return; else: a = raw_input ("enter the key"); head = linknode (k = a); if n is 1: return head; else: p = head; for I in range (1, n): a = raw_input ("enter a key"); t = linknode (k = a); p. next = t; p = t; return head; def printlist (head): # print the linked list p = head; while p! = None: print p. key; p = p. next; def listlen (head): # Calculate the length of the linked list c = 0; p = head; while p! = None: c = c + 1; p = p. next; return c; def insert (head, n): # insert the element if n <1 or n> listlen (head): return; p = head; if n is 1: a = raw_input ("enter a key"); t = linknode (k = a); t. next = head; head = t; else: for I in range (1, n-1): p = p. next; a = raw_input ("enter a key"); t = linknode (k = a); t. next = p. next; p. next = t; return head; def dellist (head, n): # Delete if n <1 or n> listlen (head): return head; elif n is 1: head = head. next; else: p = head; for I in range 1, n-1): p = p. next; q = p. next; p. next = q. next; return head; def findlist (head, n): # Find p = head; if p is None: return; while (p! = None): if p. key is repr (n): print "find it"; return 1; else: p = p. next; if p is None: print "not found ";

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.