Algorithm (algorithms) version 4th practice 1.3.20

Source: Internet
Author: User

Method implementation:

//1.3.20    /*** Delete the kth element in a linked list, if it exists. *      * @paramk the kth element, it should larger than 1 *@throwsIllegalArgumentException If k < 1 *@throwsnosuchelementexception If the size of the list is less than K*/     PublicItem Delete (intk) {if(K < 1)            Throw NewIllegalArgumentException ("K must larger than 1"); Node<Item> precurrent =NewNode<item>(); Precurrent.next=First ;                Item item;  while(Precurrent.next! =NULL&& k > 1) {precurrent=Precurrent.next; K--; }                if(Precurrent.next = =NULL)             Throw NewNosuchelementexception ("LinkedList hasn ' t so many elements"); Item=Precurrent.next.item; if(Precurrent.next = =First ) first=Precurrent.next.next; ElsePrecurrent.next=Precurrent.next.next; returnitem; }

Test Case:

 Packagecom.qiusongde.linkedlist;Importedu.princeton.cs.algs4.StdIn;ImportEdu.princeton.cs.algs4.StdOut; Public classExercise1320 { Public Static voidMain (string[] args) {LinkedList<String> list =NewLinkedlist<string>();  while(!Stdin.isempty ()) {String s=stdin.readstring ();            List.insertatbeginning (s); Stdout.println ("Insertatbeginning success:" +s);        STDOUT.PRINTLN (list); }                intK = 5; String s=List.delete (k); Stdout.println ("Delete" + k + "th Element success:" +s);                STDOUT.PRINTLN (list);  for(inti = 0; I < 4; i++) {k= 1; S=List.delete (k); Stdout.println ("Delete" + k + "th Element success:" +s);        STDOUT.PRINTLN (list); } k= 5; S=List.delete (k); Stdout.println ("Delete" + k + "th Element success:" +s);    STDOUT.PRINTLN (list); }}

Test data:

Tobeornotto

Output Result:

"Main" java.util.NoSuchElementException:LinkedList hasn ' t many elements at    Com.qiusongde.linkedlist.LinkedList.delete (linkedlist.java:130)    at Com.qiusongde.linkedlist.Exercise1320.main (Exercise1320.java:32)

Algorithm (algorithms) version 4th practice 1.3.20

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.