Problem Description: Given a single linked list, the data stored in the linked list is an integer, given an integer x, to delete all elements of the single linked list that are equal to X.
For example: single-linked list is (1,2,3,4,2,4), x=2, then the linked list is (1,3,4,4) after the node is deleted
Analysis: This is the basic operation of the list of problems, the specific Java code is as follows:
1 ImportJava.util.*;2 classnode{//the structure of a linked list node3 intdata;4Node next=NULL;5 }6 7 Public classMain {8 Public Static voidCreatelinklist (Node Head,intlength) {9Scanner scan=NewScanner (system.in);TenNode p=head; One for(inti=0;i<length;i++)//Loop to create a linked list A { -Node node=NewNode (); - intData=scan.nextint (); theNode.data=data; -p.next=node; -p=node; - } + } - Public Static voidPrintlinklist (Node head) {//recursive print chain list + if(head.next!=NULL){ ASystem.out.print (head.next.data+ "-"); at printlinklist (head.next); - } - } - Public Static voidDeletenode (Node Head,intx) {//Delete a node with a value of x in the linked list -Node p=head; -Head=Head.next; in while(head!=NULL ) - { to + if(head.data==x)//If the value of the data in the node equals x, direct the node to the next node of the next node -p.next=Head.next; the Else *p=head; $ Panax NotoginsengHead=Head.next; - } the } + Public Static voidMain (string[] args) { A //TODO Auto-generated method stubs theScanner scan=NewScanner (system.in); +Node head=NewNode (); -System.out.print ("Please enter the length of the list:"); $ intLength=scan.nextint (); $System.out.print ("Please enter the value of each node of the list:"); - createlinklist (head,length); -System.out.print ("This list is:"); the Printlinklist (head); - System.out.println ();WuyiSystem.out.print ("Enter the value of the node to be deleted:"); the intx=scan.nextint (); - Deletenode (head,x); WuSystem.out.print ("delete" +x+ "After the list is:"); - Printlinklist (head); About } $ -}
The test sample output is:
Please enter the length of the list: 6
Please enter the value of each node of the list: 1 2 3 4 2 4
This list is:1->2->3->4->2->4->
Enter the value of the node you want to delete: 2
After deleting 2, the linked list is:1->3->4->4->
Deletion of data values within nodes of a single-linked list (Ctrip written test questions)