current position:Home>Simple implementation of linked list in Java
Simple implementation of linked list in Java
2022-05-15 05:09:32【banbanbanni】
Catalog
One 、 Simple understanding of linked list
1、 What does the linked list look like ?
Two 、 Code implementation of linked list
2、 The construction of linked list
4、 Find whether to specify whether the element is in the single linked list
5、 Insert an element at a specified location in the linked list
6、 Delete the first occurrence of the specified element in the linked list
(2)、 Print the linked list from the given position
One 、 Simple understanding of linked list
In my last article, I explained the sequence table in detail , We can know that the sequential table is stored sequentially in memory , But the list that we will explain in this article is just the opposite , Linked lists are stored randomly in memory , This is also a sideshow of , Linked list is very flexible , It can make rational use of a lot of space , And through some “ Secret signal ” To realize their respective connections .
1、 What does the linked list look like ?
A linked list is composed of nodes , These nodes are just like train carriages , Connect one by one , The following figure is a linked list
2、 What is the node ?
The linked list is composed of one node, as shown in the following figure , The storage of each data in the linked list consists of the following two parts :
- The data element itself , The area where it is located is called the data field ;
- A pointer to the immediate successor element , The area where the pointer is located is called the pointer field ;
And our linked list is linked by nodes , According to the above figure, it is not difficult for us to find that a node must have two parts , One to store data , One to save the address of the next node . Through the above understanding, we almost have a preliminary understanding of the linked list , Next, we start to build our own linked list with code .
Two 、 Code implementation of linked list
1、 Construction of nodes
The construction of a linked list is inseparable from the composition of nodes , So the first step in building a linked list is, of course, to lay the foundation , Set up nodes , We can create a class to realize the creation of a node , Then assign values to the nodes by constructing the method of assignment , Of course, this reference must be a reference of this node type , Because our linked list is basically realized by pointing to the next node through the node
class NodeList{
public int date;
public NodeList next;
public NodeList(int num){
this.date = num;
}
}
2、 The construction of linked list
With nodes, we can build a linked list , First , A linked list must have a header node , If there is no head node, there will be no head of the group of dragons , All linked list data is lost , So this head node is very important , Then initialize the linked list , In fact, it is not the same as the construction of nodes , I also use a construction method to define the beginning of a linked list , But the construction method of nodes is to assign values to nodes , The linked list initialization is to build a node and assign a value to it .
public NodeList head;
public MyLinkedList(int num){
this.head = new NodeList(num);
}
3. Check the list length
To find the length of the linked list, we need to build a sentinel node to traverse the whole linked list , When the sentinel node is null when , Return to one size value .
// Get the length of the single linked list
public int size(){
int count = 0;
NodeList cur = this.head;
while(cur != null){
count++;
cur = cur.next;
}
return count;
}
4、 Find whether to specify whether the element is in the single linked list
This requires building a method with boolean type as the return value , First of all, we should establish a sentinel node , Traverse the entire list , If a node stores the same value as the specified element , return True, After traversing the linked list, it returns... Before it is found False
// Look for keywords key Is it in a single linked list
public boolean contains(int key){
NodeList cur = this.head;
while(cur != null){
if(cur.date == key){
return true;
}
cur = cur.next;
}
return false;
}
5、 Insert an element at a specified location in the linked list
This is the same as the sequence table , There are three situations
(1)、 Tail insertion
This is the simplest way to insert , Directly put the of the last node next Just point to the new node
// The tail interpolation
public void addLast(int num){
NodeList nodeList = new NodeList(num);
if(this.head == null){
this.head = nodeList;
}else{
NodeList cur = this.head;
while(cur.next != null){
cur = cur.next;
}//cur == null
cur.next = nodeList;
}
}
(2)、 Head insertion
Head insertion we need to consider the problem of head pointer , We can probably solve it in two steps :
First step , Put the new node next The pointer points to the head of the original linked list .
The second step , Change the new node into a new header pointer .
// The first interpolation
public void addFirst(int num){
NodeList nodeList = new NodeList(num);// First create a node
nodeList.next = this.head;
this.head = nodeList;
}
(3)、 Intermediate insertion
The middle insertion is also divided into two steps :
First step 、 New node next The pointer , Pointer to the insertion position
Second parts 、 Insert the position of the front node next The pointer , Point to the new node
/**
* find index-1 The address of the node of the location
* @param index
* @return
*/
public NodeList findIndex(int index){
NodeList cur = this.head;
while(index - 1 != 0){
cur = cur.next;
index--;
}
return cur;
}
/**
*
* @param index Insertion position
* @param num Insert elements
* We can judge first, then look for and then insert
*/
// Insert at any position , The first data node is 0 Subscript no.
public void addIndex(int index,int num) {
if (index < 0 || index > size()) {
System.out.println("erro");
return;
}
if(index == size()){
addFirst(num);
return;
}
if(index == size()){
addLast(num);
return;
}
NodeList nodeList = new NodeList(num);
NodeList cur = findIndex(index);
nodeList.next = cur.next;
cur.next = nodeList;
}
6、 Delete the first occurrence of the specified element in the linked list
Deleting elements and adding elements are much the same , There are also three ways
(1)、 Tail delete
Tail deletion is the simplest , Put the... Of the penultimate node next The direct point is null
(2)、 Head delete
Set the original head node of the linked list to the original head node next Just a pointer
(3)、 Delete... In the middle
Put the front-end machine node of the node to be deleted next The pointer , Point to the element to delete next Just a pointer
The premise is that we need to build a method to find the subscript of the previous node of the element to be deleted , In this way, we can get the node's next Point directly to the... Of the deleted element next
/**
* find The precursor of the keyword to be deleted
* @param key
* @return
*/
public NodeList searchPerv(int key){
NodeList cur = this.head;
while(cur != null){
if(cur.next.date == key){
return cur;
}// Note that cur.next
cur = cur.next;
}
return null;
}
// Delete the first keyword as key The node of
public void remove(int key){
if(this.head == null){
System.out.println("erro");
return;
}
if(this.head.date == key){
this.head = this.head.next;
return;
}
NodeList cur = searchPerv(key);
NodeList del = cur.next;
cur.next = del.next;
}
7、 Printing of linked list
This is very simple , We just need to traverse the linked list , Print the elements on the node in turn
(1)、 Print the whole list
public void display(){
NodeList cur = this.head;//cur To traverse the linked list
while(cur != null){
System.out.print(cur.date+" ");
cur = cur.next;
}
System.out.println();
}
(2)、 Print the linked list from the given position
/**
* Print from the specified header node
* @param newHead Given head node
*/
public void display2(NodeList newHead){
NodeList cur = newHead;
while(cur != null){
System.out.print(cur.date+" ");
cur = cur.next;
}
System.out.println();
}
8、 Empty the list
There will be a thorny problem in clearing the linked list , That is, if we release every reference from the node null, But when we release the end point reference for the first time, we will find that the whole linked list is lost , At this time, we need to set up a sentinel node , Before each release, we record the position of the header node , Then, after the head node is released , We don't have to lose our previous position
public void clear(){
while (this.head != null) {
NodeList curNext = head.next;
this.head.next = null;
this.head = curNext;
}
}
3、 ... and 、 summary
Through this article, we can find that the data structure is not so-called good or bad , The same is true for linked lists and sequential lists , It can be said that they have their own merits , Each has its own advantages , The performance of linked list and sequential list is summarized in the following table
It is not difficult to find that the advantage of the sequential table is to find and update an element , The advantage of linked list is to insert and delete .
For the combination with relatively high frequency of continuous search and update , It's better for us to choose the sequence table .
For combinations that need to be continuously inserted and deleted , We choose the best linked list .
Okay , This article is over here , I'm glad to finish this article on the eve of Liverpool's upcoming finals , I hope Liverpool can win the title !!! I am a banni, See you next time
copyright notice
author[banbanbanni],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/135/202205142226455441.html
The sidebar is recommended
- Language model what is language model?
- What platforms have the Dharma Institute language laboratory built?
- How to develop UI component library (heavy UI) based on Vue
- My colleague told me that the reason why his code is silky is that he uses mybatis plus?
- Artificial intelligence is undoubtedly a very hot research direction at present. According to the development level of artificial intelligence, which stages will researcher Shiluo divide it into?
- What are the problems and challenges of rate adaptive technology?
- How to make the video clearer?
- What is neurolinguistic model and representation learning?
- What are the two kinds of traditional language model construction?
- The best configuration for IntelliJ idea development
guess what you like
How to count the number of words in English text through C language?
On the problem of C language: the division of students' grades
The interactive search system adopts the modular design idea. According to the hierarchical logical structure, which levels are divided into?
Common problems and solutions of get technology message middleware application
How to deal with facial beauty when achieving facial beauty effect?
In order to achieve the effect of facial beauty, what are we mainly through in technology?
How to watch hot dramas on vertical screen?
Three party application login access GitHub scheme
Online FAQ positioning FAQ what does high CPU utilization mean?
Online FAQ positioning FAQ what is the cause of the high load problem?
Random recommended
- Why do we do quality evaluation?
- What is the function of getstatic, a common tool for online FAQs?
- Android 11 new soft keyboard occlusion / animation solution
- Common tools for online FAQs include?
- How does SAP commerce cloud configure new applications for storefront
- In the CMS GC process, what is the reason why the business thread puts objects into the old generation (the characteristics of concurrent collection)?
- How good and accurate is the recommendation?
- Online FAQ positioning FAQs what are the causes of continuous GC problems?
- Does the data reflect the real viewing experience?
- What are the reasons for fullgc (throw oom if FGC recovery is invalid)?
- Algorithm improvement - basic algorithm (turtle speed multiplication)
- [C + +] sword finger offer 10 - I. Fibonacci sequence
- Online FAQ positioning FAQ nosuchmethodexception what is the cause of the problem?
- IOS enables native im development
- What is the common function of SM?
- "Automated testing" a new generation of Web front-end automated testing framework - playwright, get started quickly!
- Online FAQ positioning FAQ what is the cause of the high load problem?
- What is the function of watch, a common tool for online FAQs?
- Timeliness in recommender systems, Zhang Fuguo et al. ESWA 2017
- Alibaba's open source Java diagnostic tool uses what methods to diagnose.
- What is the function of dashboard, a common tool for online FAQs?
- What is the role of JAD, a common tool for online FAQs?
- Online FAQ positioning FAQ what are the causes of high CPU utilization?
- 07 - explore the underlying principles of IOS | several OC objects [instance object, class object, metaclass], ISA pointer of object, superclass, method call of object and the underlying essence of class
- Extreme fox gitlab settled in Alibaba cloud computing nest to jointly improve the development experience on the cloud
- How does artificial intelligence help natural science
- Elementui upload file
- Modern CSS solution: CSS mathematical functions
- Create a general efficiency improvement solution for front desk + middle desk based on vue3 (network disk link)
- Brush 100 front-end high-quality interview real questions in 2 weeks, and the source code is complete
- Vue has reduced its workload by half since using components
- I built a front-end mock tool
- About uboot -- Ping virtual machine Ubuntu operation
- Video transcoder editready for Mac
- [taro] taro gets the detailed attributes of the element (solved)
- Picture and text difference comparison tool: kaleidoscope for Mac
- Background of spatiotemporal artificial intelligence
- The top 10 of oceanbase database competition was born, and the integration of industry and education accelerated the training of database talents
- China brand Day | Youxuan software: strengthen its own brand and fight for China's database industry
- New feature release of gaussdb (for redis): enhanced prefix scanning and multi rent isolation