Create an instance of a linked list separately with C and Java _java

Source: Internet
Author: User
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;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.