Create instances of linked lists in C and JAVA respectively

  • 2020-04-01 02:21:59
  • OfStack

Operations such as creating linked lists, inserting data into linked lists, and deleting data, take single linked lists as an example.
1. Create a linked list using C language:

typedef struct nd{
  int data;
  struct nd* next; } node;
//Initialize to get a chain header node
node* init(void){
   node* head=(node*)malloc(sizeof(node));
  if(head==NULL) return NULL;
  head->next=NULL;
  return head;
}
//Insert data at the end of the 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 ACTS as the tail node of the list
  p->next=new;//Links the new node to the end 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 is the header node the node to be deleted
    head=head->next;//The head node of the updated list is the next node of the head node
    free(p);
    return;
  }
  node *q=head->next;
  while(q!=NULL){
     if(q->data==data){//Find the node q to delete
      node *del=q;
      p->next=q->next;
       free(del);
     }
    p=q;//If the node is not to be deleted, update p and q and continue to look for it
    q=q->next;
   }
}

2. Create linked lists in Java
Create a linked list

class Node {
  Node next = null;
   int data;
  public Node(int d) { data = d; }
  void appendToTail(int d) {//Add data to the end 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

Node deleteNode(Node head, int d) {
   Node n = head;
  if (n.data == d) { return head.next;  }
  while (n.next != null) {
    if (n.next.data == d) {
       n.next = n.next.next;
       return head; 
    } n = n.next;
   }
}

Related articles: