Create a linked list, insert data into a linked list, delete data, and so on, using a single linked list as an example.
1. Create a linked list using the C language:
Copy Code code as follows:
typedef struct nd{
int data;
struct nd* next; node;
Initialize to get a linked table header node
node* init (void) {
node* head= (node*) malloc (sizeof (node));
if (head==null) return NULL;
head->next=null;
return head;
}
Inserting data at the end of a linked list
void Insert (node* head,int data) {
if (head==null) return;
node* P=head;
while (P->next!=null)
p=p->next;
node* new= (node*) malloc (sizeof (node));
if (new==null) return;
new->data=data;
new->next=null;//the new node as the tail node of the linked list
p->next=new;//links new nodes to the tail of the list
}
Deletes a node from the list, where the return value is null, that is, the deleted node is not returned
void Delete (node* head,int data) {
if (head==null) return;
Node *p=head;
if (head->data==data) {//How the header node is the node to be deleted
head=head->next;//Update the header node of the linked list as the next node of the head node
Free (p);
Return
}
Node *q=head->next;
while (Q!=null) {
if (q->data==data) {//Find the node to delete q
Node *del=q;
p->next=q->next;
Free (DEL);
}
p=q;//is not the node to be deleted, update p, Q, and continue looking backward
q=q->next;
}
}
2.Java Create a linked list
Create a linked list
Copy Code code as follows:
Class Node {
Node next = null;
int data;
Public Node (int d) {data = D;}
void Appendtotail (int d) {//Add data to the tail of the list
Node end = new node (d);
Node n = this;
while (N.next!= null) {n = n.next;}
N.next = end;
}
}
Remove a node from a single linked list
Copy Code code as follows:
Node Deletenode (node head, int d) {
Node n = head;
if (N.data = = d) {return head.next/* moved head */}
while (N.next!= null) {
if (N.next.data = = d) {
N.next = N.next.next;
return head; /* head didn ' t change * *
} n = n.next;
}
}