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