Note the restriction constraints in the INSERT and delete operations.
classListNode {ListNode next; intVal; PublicListNode (intx) {val=x; }} Public classlinklist {PrivateListNode Curr =NULL; Public voidAppendtohead (intd) {ListNode tail=NewListNode (d); Tail.next=Curr; Curr=tail; } Public voidPrintappendtohead () { while(Curr! =NULL) {System.out.println (curr.val); Curr=Curr.next; } } Public voidDeleteintDthrowsException {//assume that the element you want to delete appears only once in the linked list. if(Curr = =NULL)Throw NewException ("Empty linklist"); if(Curr.val = = d) {Curr = Curr.next;return;} ListNode tmp=Curr; while(Tmp.next! =NULL) { if(Tmp.next.val = = d) {tmp.next = Tmp.next.next;return;} TMP=Tmp.next; } return; } Public voidInsertintD) {//assume that the elements in the list are sorted in descending order. if(Curr = =NULL) {Curr =NewListNode (d);return;} if(D >curr.val) {listnode tmp=NewListNode (d); Tmp.next=Curr; Curr=tmp; return; } ListNode currtmp=Curr; while(Currtmp.next! =NULL) { if(D >currTmp.next.val) {listnode tmp=NewListNode (d); Tmp.next=Currtmp.next; Currtmp.next=tmp; return; } currtmp=Currtmp.next; } listnode tmp=NewListNode (d); Currtmp.next=tmp; return; } Public Static voidMain (string[] args)throwsException {int[] Array =New int[] {1, 2, 2, 3, 4}; Linklist llist=Newlinklist (); for(inti = 0; i < Array.Length; i++) {llist.appendtohead (array[i]); }//Llist.delete (3);Llist.insert (0); Llist.printappendtohead (); }}
One-way linked list Delete and insert operation (the one-way linked list is established by the head insertion method)