Java implements a linked list

Source: Internet
Author: User

Java implements a linked list

Public class MyList {static class Node {// Node class Object data; Node next; public Node (Object data) {// constructor, assign this to data. data = data; this. next = null ;}} Node head; public MyList () {head = null; // constructor} public void clear () {// clear linked list head = null ;} public void bianli () // traverse {Node p = head; while (p! = Null) {System. out. print (p. data + ""); p = p. next;} System. out. println ();} public boolean isEmpty () // judge whether it is null {return head = null;} public int size () {// number of nodes Node p = head; int sum = 0; while (p! = Null) {sum ++; p = p. next;} return sum;} // insert an element at the specified position. The subscript starts from 0 and public void insert (Object d, int pos) {if (pos <0 | pos> size () {throw new RuntimeException ("subscript error");} Node newNode = new Node (d ); if (pos = 0) {newNode. next = head; head = newNode;} else if (pos> = size ()-1) {get (size ()-1 ). next = newNode;} else {newNode. next = get (pos); get (pos-1 ). next = newNode;} public Node get (int pos) {if (pos <0 | pos> size () {throw new RuntimeException ("subscript error ");} if (pos = 0) return head; Node p = head; for (int I = 0; I <pos; I ++) p = p. next; return p;} public static void main (String [] args) {MyList list = new MyList (); list. insert (10, 0); list. insert (20, 1); list. insert (30, 0); list. insert (40, 1); System. out. println (list. size (); list. bianli (); System. out. println (list. isEmpty (); System. out. println (list. get (2 ). data); list. clear (); System. out. println (list. isEmpty ());}}

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.