The establishment and basic operation of single linked list in C + + _c language

Source: Internet
Author: User

Preparing data

Prepare variables and data structures to be used in linked list operations

The sample code is as follows:

Copy Code code as follows:

struct Data//node type
{
String key; Key words
String name;
int age;
};
struct Cltype//definition of linked list structure
{
Data Nodedata;
Data *nextnode;
};

Defines the type of data elements of a linked list and the structure Cltype of the linked list. The specific data of the node is stored in a structure, and the pointer nextnode is used to point to the next node.

We can think that the list is a record of a class of students, where key is the number of students, name is the name of the student, age is ages.

Append nodes

Append node is to add a node at the end of the list. The address portion of the footer node was originally saved with an empty address null, which needs to be set to the address of the new node (that is, the original table end node points to the new knot), and then the address portion of the new nodes is set to an empty address null, that is, the new knot is footer

Because in general, a linked list has only one head pointer to it, adding a node at the end needs to be checked from head to toe until the last node (the footer) is found.

The procedure for appending nodes is as follows:

(1) First allocates the memory address, saves the new node.

(2) Start by examining the head pointer, until you find the last node (that is, the end of the table).

(3) Set the address of the footer node to the address of the new node.

(4) Set the address portion of the new node to null address, that is, the new node becomes the footer.

The sample code is as follows:

Copy Code code as follows:

Cltype * Claddend (cltype *head,data nodedata)
{
 cltype *node,*h Temp
 if (!) ( node = new Cltype))
 {
  cout<< allocating memory failed! "<<endl;  //failed to allocate memory
  return NULL;
 }
 else
 {
  node->nodedata = nodedata;   //Save node Data
   Node->nextnode = NULL;     //sets the node pointer to null, which is the footer
  if (head = = NULL)       // When the list is empty,
  {
   head = node;
   return Head;
  }
  htemp = head;
  while (Htemp->nextnode!= NULL)    //Find the end of the list
  {
    htemp = htemp->nextnode; 
  }
  htemp->nextnode = node;
  return Head;
 }

}

The input parameter head is a chain header pointer, and the input parameter nodedata the data saved by the node. program, the new keyword is used to request dynamic space, and if the allocation succeeds, node will hold a pointer to the memory area.

The incoming nodedata is then saved to the requested memory area, and the pointer value of the node to the next node is set to null.

Insert Header Node

The Insert Header node is the process of adding a node in the header of the list, and instead of inserting a node at the end of the table, the operation is to insert a node on the header as the header node.

The steps for inserting a header node are as follows:

(1) First allocates the memory, saves the new node.

(2) Add the new sibling point to the head pointer to the node

(3) Then the head pointer heads point to the new node.

The sample code is as follows:

Copy Code code as follows:

Cltype *claddfirst (cltype *head,data nodedata)
{
Cltype *node;
if (!) ( node = new Cltype))
{
cout<< "Allocate memory Failed" <<endl;
return NULL;
}
Else
{
Node->nodedata = Nodedata; Save the node data.
Node->nextnode = head; Point to Pointer to head pointer
Head = node; The head pointer points to the new node.
return head;
}
}

The input parameter head is a chain header pointer, and the input parameter nodedata the data saved in the node. In the program, the New keyword is used first to request the memory space of the Save node, and if the request succeeds, a pointer to the memory area will be saved in node.

The incoming nodedata is then saved to the requested memory area, and the new node points to the node to which the header head is pointed, and then sets the head pointer to point again to the new node.

Finding nodes

Finding a node is finding the required element in the list structure. For the linked list structure, generally can be divided into according to the number of nodes to find and according to the keyword query two categories.

Query by node serial number.

That is, the number of nodes in the query list, the sample code is as follows:

Copy Code code as follows:

Cltype *clfindnodenum (Cltype *head,int k)
{
Cltype *htemp;
int i = 1;
Htemp = head; Save a list header pointer
for (i = 1;i<k&&htemp;i++)//Find the Node
{
Htemp = htemp->nextnode;
}
return htemp; Returns a pointer to the K node
}

The input parameter head is a chain header pointer, and the input parameter k is the ordinal of the node to be queried. Loop through the ordinal number, get a pointer to the node, and return the pointer.

Search by keyword

That is, according to the node in the list of a keyword query, we query the student's name (name) For example, the sample code is as follows:

Copy Code code as follows:

Cltype *clfindnodekey (cltype *head,string name)
{
Cltype * HTEMP;
Htemp = head; Save a list header pointer
while (htemp)
{
if (htemp->nodedata.name = = name)//When the node keyword is the same as the incoming key word
{
return htemp; Returns the node pointer
}
Htemp = htemp->nextnode;
}
return NULL;
}

The input parameter head is the list header pointer, and the input parameter name is the name of the classmate to query. Iterate through the names of all the students in the query, and when the name of the node is the same as the queried name, the pointer to the node is returned.

Inserting nodes

Inserting a node adds a node to the middle of the list.

The steps to insert a node are as follows:

(1) Allocate the memory space, save the new node.

(2) Find the logical position to insert, that is, find the back of the node that is plugged in.

(3) Modify the pointer to the insertion position node to point to the new node, and make the new node point to the node that the original insertion position points to.

The sample code is as follows:

Copy Code code as follows:

Cltype *clinsertnode (cltype *head,int k,data)
{
  Cltype *node,*nodetemp;
 if (!) ( node = new Cltype)     //request node
 {
  cout<< "Request memory Failure" <<endl;
  return NULL;
 }
 else
 {
  node->nodedata = nodedata;  //save data in a node
   Nodetemp=clfindnodenum (head,k-1); Finds a node before the insertion point (key node)
  if (nodetemp)
by following the node ordinal lookup function   {
   node->nextnode = nodetemp->nextnode;//inserted nodes point to the next node of the key point
    Nodetemp->nextnode = node;   //Key node point to insertion point
  
  else
  {
   cout<< "did not find the correct insertion location" <<endl;
   delete node;
  }
 }
 return head;      //return head pointer


The input parameter head is the chain header pointer, the input parameter FindKey is the node that searches in the linked list, after finding the node, the node data is added after the node, and Nodedata is the data of the new node. The program first uses new to request the node space, and then calls the Clfindnodenum function to find points to the node, and then perform the insert operation.

Delete a node

The deletion of a node is the deletion of a node data in the linked list, which does not affect the node before and after its location.

The steps to delete a node operation are as follows:

(1) Find the node that needs to be deleted.

(2) Make the previous node point to the next knot of the current nodes.

(3) Delete the node

Delete nodes can be determined by the number of nodes to delete the node, of course, you can also through the keyword node to determine the node to be deleted.

Let's take the keyword to delete the node for example, the sample code is as follows:

Copy Code code as follows:

int Cldeletenode (cltype *head,string name)
{
Cltype *node,*htemp; node is used to delete the previous node of a node
Htemp = head;
node = head;
while (htemp)
{
if (htemp->nodedata.name = = name)//Find the keyword, perform the delete operation
{
Node->nextnode = htemp->nextnode;//Causes the previous node to point to the next knot in the current point
Delete htemp; Free space for the node (that is, delete the endpoint)
return 1;
}
Else
{
node = htemp; Point to current node
Htemp = htemp->nextnode; Point to the next node.
}
}
return 0; Delete failed
}

Head is a chain header pointer, and the input parameter name indicates the name of the classmate you want to delete. In the program, through a loop, in the whole list by keyword to find the node to delete. If a deleted node is found, the previous node (node pointer point) is set to the next node of the current node (the node to which the H pointer refers). That is, the node is logically deleted, then a delete operation is performed on the node, freeing the memory space occupied by the node, that is, physically deleting it.

Calculate the length of a linked list

Calculating the length of a linked list is the number of nodes in the list. It is convenient to calculate the length of the linked list in the sequential table, but the length of the linked list in the linked list needs to be obtained by traversing the linked list, because the linked list is not stored continuously in the physical.

The sample code is as follows:

Copy Code code as follows:

int Cllength (Cltype *head)
{
Cltype *htemp;
int Len = 0;
Htemp = head;
while (htemp)//traverse the entire array
{
len++; Number of cumulative nodes
Htemp = htemp->nextnode; Handle the next node.
}
return Len;
}

The parameter head is the header of the linked list, in which the pointer is traversed by a while in the program, Len as the counter, and the number of times the loop is recorded to obtain the length of the list, when the pointer is null, and then the value of the counter is returned.

Show all nodes

Iterate through all the nodes and output.

Copy Code code as follows:

void Clallnode (Cltype *head)
{
Cltype *htemp;
Htemp = head;
while (htemp)//traverse the entire array
{
Nodedata = htemp->nodedata; Get the node data.
cout<< "key:" <<nodeData.key<< ", Name:" <<nodeData.name<< ", Age:" <<nodedata.age <<endl;
Htemp = htemp->nextnode; Handle the next node.
}
}

Output node function, no return value, all defined as void. Each time the value of its nodedata is obtained through a cltype type of node.

Complete example of a linked list operation

The code for the complete example is longer, so be patient ...:)

Copy Code code as follows:

#include <iostream>
#include <string>
using namespace Std;
struct Data//node type
{
String key; Key words
String name;
int age;
};
struct Cltype//definition of linked list structure
{
Data Nodedata;
Cltype *nextnode;
};
Cltype * Claddend (cltype *head,data nodedata)
{
Cltype *node,*htemp;
if (!) ( node = new Cltype))
{
cout<< failed to allocate memory!  "<<endl; Allocating memory failed
return NULL;
}
Else
{
Node->nodedata = Nodedata; Save the node data.
Node->nextnode = NULL; Sets the node pointer to null, which is the footer of the table.
if (head = = NULL)//When the list is empty
{
Head = node;
return head;
}
Htemp = head;
while (Htemp->nextnode!= NULL)//Find the end of a list
{
Htemp = htemp->nextnode;
}
Htemp->nextnode = node;
return head;
}

}
Cltype *claddfirst (cltype *head,data nodedata)
{
Cltype *node;
if (!) ( node = new Cltype))
{
cout<< "Allocate memory Failed" <<endl;
return NULL;
}
Else
{
Node->nodedata = Nodedata; Save the node data.
Node->nextnode = head; Point to Pointer to head pointer
Head = node; The head pointer points to the new node.
return head;
}
}
Cltype *clfindnodenum (Cltype *head,int k)
{
Cltype *htemp;
int i = 1;
Htemp = head; Save a list header pointer
for (i = 1;i<k&&htemp;i++)//Find the Node
{
Htemp = htemp->nextnode;
}
return htemp; Returns a pointer to the K node
}
Cltype *clfindnodename (cltype *head,string name)
{
Cltype * HTEMP;
Htemp = head; Save a list header pointer
while (htemp)
{
if (htemp->nodedata.name = = name)//When the node keyword is the same as the incoming key word
{
return htemp; Returns the node pointer
}
Htemp = htemp->nextnode;
}
return NULL;
}
Cltype *clinsertnode (cltype *head,int k,data nodedata)
{
Cltype *node,*nodetemp;
if (!) ( node = new Cltype)/Application node
{
cout<< "Request memory Failed" <<endl;
return NULL;
}
Else
{
Node->nodedata = Nodedata; Save data in a node
Nodetemp=clfindnodenum (head,k-1); Find a node (key node) before the insertion point by finding a function according to the node ordinal.
if (nodetemp)
{
Node->nextnode = nodetemp->nextnode; The node that is inserted points to the next nodes of the key knot.
Nodetemp->nextnode = node; Key node points to insertion point
}
Else
{
cout<< "did not find the correct insertion location" <<endl;
Delete node;
}
}
return head; Return header pointer
}
int Cldeletenode (cltype *head,string name)
{
Cltype *node,*htemp; node is used to delete the previous node of a node
Htemp = head;
node = head;
while (htemp)
{
if (htemp->nodedata.name = = name)//Find the keyword, perform the delete operation
{
Node->nextnode = htemp->nextnode; Causes the previous node to point to the next knot in the current point
Delete htemp; Free space for the node (that is, delete the endpoint)
return 1;
}
Else
{
node = htemp; Point to current node
Htemp = htemp->nextnode; Point to the next node.
}
}
return 0; Delete failed
}
int Cllength (Cltype *head)
{
Cltype *htemp;
int Len = 0;
Htemp = head;
while (htemp)//traverse the entire array
{
len++; Number of cumulative nodes
Htemp = htemp->nextnode; Handle the next node.
}
return Len;
}
void Clallnode (Cltype *head)
{
Cltype *htemp;
Data Nodedata;
Htemp = head;
cout<< "Linked list length:" <<cllength (head) <<endl;
while (htemp)//traverse the entire array
{
Nodedata = htemp->nodedata; Get the node data.
cout<< "key:" <<nodeData.key<< ", Name:" <<nodeData.name<< ", Age:" <<nodedata.age <<endl;
Htemp = htemp->nextnode; Handle the next node.
}
}
int main ()
{
Cltype *node,*head = NULL;
Data Nodedata;
String name;
int k;
cout<< "Please enter the data in the list, the format is: School number, name, age (age is 0 o'clock stop typing)" <<endl;
while (1)
{
cin>>nodedata.key>>nodedata.name>>nodedata.age;
if (nodedata.age==0) break;
Head=claddend (Head,nodedata); Add a node at the end of the list
}
Clallnode (head); Show all the nodes.
Demonstrates inserting data in the header
cout<< "Please enter a node and insert it in the head of the list" <<endl;
cin>>nodedata.key>>nodedata.name>>nodedata.age;
Head=claddfirst (Head,nodedata);
Clallnode (head);
Demonstrates inserting a data in an intermediate location
cout<< "Please enter a node inserted inside the list:" <<endl;
cin>>nodedata.key>>nodedata.name>>nodedata.age;
cout<< "Please enter the location of the insertion point:";
cin>>k;
Head=clinsertnode (Head,k,nodedata);
Clallnode (head);
Demo query data by ordinal
cout<< "Please enter a node number according to the node query:";
cin>>k;
Node=clfindnodenum (HEAD,K);
cout<< "The node you are querying is:" <<endl;
cout<< "key:" <<node->nodeData.key<< ", Name:" <<node->nodeData.name<< ", Age:" <<node->nodeData.age<<endl;
Demo query data by name
cout<< "Please enter the name of a classmate who is queried by name:";
cin>>name;
Node=clfindnodename (Head,name);
cout<< "The node you are querying is:" <<endl;
cout<< "key:" <<node->nodeData.key<< ", Name:" <<node->nodeData.name<< ", Age:" <<node->nodeData.age<<endl;
Demo Delete Data information
cout<< "Please enter the name of a classmate in the node, the system will delete his message:";
cin>>name;
if (Cldeletenode (head,name)) cout<< "Data deletion succeeded!" "<<endl;
Clallnode (head);
return 0;
}

Sample program Run Results:

Related Article

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.