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:
Import Java.util.*;class The structure of the node{//linked list node int data; Node Next=null;} public class Main {public static void Createlinklist (Node head,int length) {Scanner scan=new Scanner (system.in) ; Node P=head; for (int i=0;i<length;i++)//loop build linked list {node node=new node (); int Data=scan.nextint (); Node.data=data; P.next=node; P=node; }} public static void Printlinklist (Node head) {///recursive Print List if (head.next!=null) {System . Out.print (head.next.data+ "); Printlinklist (Head.next); }} public static void Deletenode (node Head,int x) {//deletes the value in the list of nodes of the X-p=head; Head=head.next; while (Head!=null) {if (head.data==x)//If the value of the data in the node equals x, the section is directly Point points to the next node P.next=head.next; else P=head; Head=head.next; }} public static void Main (string[] args) {//TODO auto-generated method stub Scanner scan=new Scanner (system.in); Node head=new node (); System.out.print ("Please enter the length of the linked list:"); int Length=scan.nextint (); System.out.print ("Please enter the value of each node of the list:"); Createlinklist (head,length); System.out.print ("This list is:"); Printlinklist (head); System.out.println (); System.out.print ("Enter the value of the node to be deleted:"); int X=scan.nextint (); Deletenode (HEAD,X); System.out.print ("delete" +x+ "after the linked list is:"); Printlinklist (head); }}
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)