Create, insert, and delete linked lists

Source: Internet
Author: User

Array is a collection of similar data, which brings us a lot of convenience and flexibility in programming. However, arrays also have some disadvantages. For example, the size of an array must be specified in advance during definition and cannot be adjusted in the program. In this way, three zero-size arrays are sometimes required for different problems in the program design, sometimes the size of 5 0 arrays is required,
It is difficult to unify. We can only define arrays based on the maximum possible requirements, which often results in a waste of storage space.
We hope to construct a dynamic array and adjust the size of the array at any time to meet the needs of different problems. The linked list is the dynamic array we need. It applies to the system for storage space as needed during the execution of the program, and never constitutes a waste of storage space.
A linked list is a complex data structure. The relationship between its data divides the linked list into three types: single-chain table, circular linked list, and two-way linked list. The following describes them one by one.
7.4.1 single-chain table
Figure 7-3 shows the structure of a single-chain table.

A single linked list has a head node, he a D, pointing to the first address of the linked list in the memory. The data type of each node in the linked list is a struct type, and the node has two members: integer members (the actual data to be saved) and the pointer to the next struct type node is the address of the next node (in fact, this single-chain table is a dynamic array used to store integer data ). The linked list needs to start from the head of the linked list for access to each node based on this structure, and the address of subsequent nodes is provided by the current node. No matter which node you access in the table, you must start from the head of the linked list and search for it in sequence. Because no subsequent node exists at the end of the linked list, the pointer field is null and the writing is n u L.
Figure 7-3 also provides the following meanings: the memory storage addresses of nodes in the linked list are not consecutive, and the addresses of each node are allocated to the system when necessary, based on the current memory situation, the system can allocate addresses consecutively or in a leaping manner.
Let's take a look at the data structure definition of the linked list node:
Struct Node
{
Int num;
Struct node * P;
};
In the definition of a linked list node, except for an integer Member, member P points to a pointer of the same type as the node.
In the data structure of the linked list node, a very special point is that the data type of the pointer field in the structure uses the undefined successful data type. This is the only rule in C that the data structure can be used first and then defined.
? The process of creating a single-chain table is as follows:
1) define the data structure of the linked list.
2) create an empty table.
3) use the m a l o C () function to allocate a node to the system.
4) assign a null value to the pointer member of the new node. If the table is empty, connect the new node to the header. If the table is not empty
The node is connected to the end of the table.
5) check whether any subsequent node is connected to the linked list. If any, go to 3). Otherwise, it will end.
? The output process of a single-chain table is as follows:
1) locate the header.
2) if it is a non-empty table and the value member of the output node is an empty table, exit.
3) track the growth of the linked list, that is, find the address of the next node.
4) to 2 ).
[Example 7-5] create a single-chain table that stores a positive integer (input-9 9 9 as the ending sign) and print the output.
# Include <stdlib. h>/package * header file containing MA l o C */
# Include <stdio. h>
Struct node/* structure of the linked list node */
{
Int num;
Struct node * next;
};
M a I n ()
{
Struct node * creat ();/* function declaration */
Void print ();
Struct node * head;/* define the header pointer */
Head = NULL;/* Create an empty table */
Head = creat (head);/* create a single-chain table */
Print (head);/* print a single-chain table */
}
/*************************************** ***/
Struct node * creat (structnode * head) letter/Number * returns pointers of the same type as the node */
{
Struct node * P1, * P2;
P1 = P2 = (structnode *) malloc (sizeof (structnode); Apply/* New node */
Scanf ("% d", & P1-> num);/* enter the node value */
P1-> next = NULL;/* set the pointer of the new node to null */
While (P1-> num> 0)/* the value of the input node is greater than 0 */
{
If (Head = NULL) Head = p1;/* empty table, access header */
Elsep2-> next = p1;/* non-empty table, connected to the end of the table */
P2 = p1;
P1 = (structnode *) malloc (sizeof (structnode); application/Request * Next new node */
Scanf ("% d", & P1-> num);/* enter the node value */
}
Return head;/* return the head pointer of the linked list */
}
/*************************************** ****/
Void print (struct node * head): Input/* output the value of each node in the chain table with head as the header */
{
Struct node * temp;
Temp = head;/* Get the head pointer of the linked list */
While (temp! = NULL)/* as long as the table is not empty */
{
Printf ("% 6D", temp-> num);/* output the value of the linked list node */
Temp = temp-> next;/* track the growth of linked lists */
}
}
In the process of creating a linked list, the head pointer of the linked list is a very important parameter. Because the output and query of the linked list start from the head of the linked list, after the linked list is created successfully, the address of the head node of the linked list is returned, that is, the head pointer.

7.4.2 insert and delete a single-chain table
In the special data structure of the linked list, the length of the linked list needs to be set according to the specific situation. When you need to save the data, apply for a storage space from the system and connect the data to the linked list. For the linked list, the data in the table can be connected to the end of the table or the header, or inserted into the table as needed. For data that is no longer needed, delete it from the table and release its space, but it cannot break the structure of the linked list. The following describes how to insert and delete a linked list.
1. delete a linked list
Delete a node from the linked list, as shown in figure 7-4:
[Example 7-6] create a single-chain table of student ID and name, that is, the node includes student ID, name, and pointer to the next node. The linked list is arranged by student ID. Enter a student's name on the keyboard and delete it from the linked list.
First, define the structure of the linked list:
Struct
As shown in figure 7-4, you can delete a node from the linked list in three cases: deleting the head node of the linked list and deleting
Between Nodes, delete the end node of the linked list. If the name of the student is given, you should search for each section from start to end in the linked list.
Point, and compare it with the Student name of each node. If it is the same, the search is successful. Otherwise, the node cannot be found. Due to the deleted Section
Points may be in the head of the linked list, which may cause loss of the head pointer of the linked list. Therefore, the return value of the function for deleting a node is defined
Returns the pointer of the struct type.
Struct node * delet (Head, pstr) uses/* He a D as the header pointer to delete the node where Ps t r is located */
Struct node * head;
Char * pstr;
{
Struct node * temp, * P;
T e m p = h e a d;/* head pointer of the linked list */
If (Head = NULL)/* empty linked list */
Printf ("\ NLIST is null! \ N ");
Else/* non-empty table */
{
T e m p = h e a d;
While (strcmp (temp-> STR, pstr )! = 0 & temp-> next! = NULL)
/* If the node string is different from the input string and is not at the end of the linked list */
{
P = t e m p;
T e m p = t e m p-> n e x T;/* track the growth of the linked list, that is, move the pointer behind */
}
If (strcmp (temp-> STR, pstr) = 0)/* Find the string */
{
If (temp = head) {/* Header node */
Printf ("delete string: % s \ n", temp-> Str );
H e a d = h e a D-> n e x T;
F r e (t e m p);/* release deleted vertices */
}
E L S E
{
P-> next = temp-> next;/table * node */
Printf ("delete string: % s \ n", temp-> Str );
F r e (t e m p );
}
}
Else printf ("\ Nno find string! \ N "); no/found * string to be deleted */
}
R e t u r n (h e a d);/* returns the header pointer */
}
2. Insert a linked list
First, define the structure of the linked list:
Struct
{
Int num;/* student ID */
Char STR [20];/* name */
Struct node * next;
};
In the created single-chain table, there are three scenarios for inserting nodes, as shown in 7-5.

The inserted node can be at the header, table, or end of the table. Assuming that we create a linked list in the order of student IDs, the inserted nodes are compared with the nodes in the table to find the Insertion Location. Because the inserted node may be in the head of the linked list, the head pointer of the linked list will be modified. Therefore, the return value of the function defining the inserted node is defined as a pointer of the return struct type. Node
The insert function is as follows:
Struct node * insert (Head, pstr, N)/* Insert a node whose student ID is N and whose name is p s t r */
Struct node * head;/* head pointer of the linked list */
Char * pstr;
Int N;
{
Struct node * P1, * P2, * P3;
P1 = (struct node *) malloc (sizeof (struct node); with/* A new node */
S t r c p y (P 1-> s t r, p s t r);/* Name string of the write node */
P 1-> n u m = N;/* student ID */
P 2 = h e a d;
If (Head = NULL)/* empty table */
{
Head = p1; P1-> next = NULL;/* Insert the header of the new node */
}
E L S E
{/* Non-empty table */
While (n> P2-> num & p2-> next! = NULL)
/* The entered student ID is smaller than the student ID of the node and is not at the end of the table */
{
P 3 = P 2;
P 2 = P 2-> n e x T;/* track linked list growth */
}
If (n <= P2-> num)/* locate the insert position */
If (Head = P2)/* Insert position in the header */
{
H e a d = P 1;
P 1-> n e x T = P 2;
}
E L S E
{/* Insert Location in the table */
P 3-> n e x T = P 1;
P 1-> n e x T = P 2;
}
E L S E
{/* Insert at the end of the table */
P 2-> n e x T = P 1;
P 1-> n e x T = n u L;
}
}
R e t u r n (h e a d);/* return the head pointer of the linked list */
}
3. instance [Example 7-7]
Create a single-chain table containing student ID and Name node. There are any number of nodes in the table. The table is in the order of student numbers. The number of lower student numbers is in the front, the number of higher student numbers is in the back, and the input name is blank. In this linked list, you must delete a node with a given name and insert a node with a given student ID and name.
# Include "stdlib. H"
# Include "malloc. H"
Struct node/* Data Structure of the node */
{
Int num;
Char STR [20];
Struct node * next;
};
/****************************/
Main ()
{
/* Function declaration */
Struct node * creat ();
Struct node * insert ();
Struct node * delet ();
Void print ();
Struct node * head;
Char STR [20];
Int N;
Head = NULL;/* short table */
Head = creat (head);/* call the function to create a chain table with the head as the header */
P r I n t (H E A D);/* call the function output node */
Printf ("\ N input inserted num, name: \ n ");
Gets (STR);/* enter the student ID */
N = atoi (STR );
Gets (STR);/* enter name */
Head = insert (Head, STR, n); insert/* node into the linked list */
Print (head);/* call the function output node */
Printf ("\ N input deleted name: \ n ");
Gets (STR);/* enter the name to be deleted */
Head = delet (Head, STR); // call the * function to delete a node */
Print (head);/* call the function output node */
R e t u r N;
}
/**********************/
/***** Create a linked list ************/
Struct node * creat (struct node * head)
{
Char temp [30];
Struct node * PL, * P2;
PL = P2 = (struct node *) malloc (sizeof (struct node ));
Printf ("input num, name: \ n ;")
Printf ("Exit: Double times enter! \ N ");
G e t s (t e m p );
Gets (P1-> Str );
Pl-> num = atoi (temp );
P l-> n e x T = n u L;
While (strlen (pl-> Str)> 0
{
If (Head = NULL) Head = pl;
Else P2-> next = p1;
P 2 = p l;
PL = (struct node *) malloc (sizeof (struct node ));
Printf ("input num, name: \ n ");
Printf ("Exit: Double times enter! \ N ");
G e t s (t e m p );
Gets (pl-> Str );
P1-> num = atoi (temp );
P 1-> n e x T = n u L;
}
Return head;
}
/********************/
/*********** Insert a node **********/
Struct node * insert (Head, pstr, N );
Struct node * head;
Char * pstr;
Int N;
{
Struct node * PL, * P2, * P3;
P1 = (struct node *) malloc (sizeof (struct node ));
Strcpy (P1-> STR, pstr );
P 1-> n u m = N;
P 2 = h e a d;
I f (h e a d = n u L)
{
H e a d = p l; p l-> n e x T = n u L;
}
E L S E
{
While (n> P2-> num & p2-> next! = NULL)
{
P 3 = P 2
P 2 = P 2-> n e x T;
}
If (n <= P2-> num)
If (Head = P2)
{
H e a d = p l;
P l-> n e x T = P 2;
}
Else
{
P 3-> n e x T = p l;
P l-> n e x T = P 2;
}
Else
{
P 2-> n e x T = p l;
P l-> n e x T = n u L;
}
}
R e t u r n (h e a d );
}
/*************************/
/****** Delete a node *************/
Struct node * delet (Head, pstr)
Struct node * head;
Char * pstr;
{
Struct node * temp, * P;
T e m p = h e a d;
If (Head = NULL)
Printf ("\ NLIST is null! \ N ");
Else
{
T e m p = h e a d;
While (strcmp (temp-> STR, pstr )! = O & temp-> next! = NULL)
{
P = t e m p;
T e m p = t e m p-> n e x T,
}
I f (S T R C m p (t e m p-> S T R, P S T R) = 0)
{
If (temp = head)
{
H e a d = h e a D-> n e x T;
F r e (t e m p );
}
Else
{
P-> next = temp-> next;
Printf ("delete string: % s \ n", temp-> Str );
F r e (t e m p );
}
}
Else printf ("\ Nno find string! \ N ");
}
Return (head );
}
/**********************************/
/*********** Output of each node in the linked list **********/
Void print (struct node * head)
{
Struct node * temp;
T e m p = h e a d;
Printf ("\ N output strings: \ n ");
While (temp! = NULL)
{
P r I n t f ("\ n % d---% s \ n", T E m p-> n u m, t e m p-> s t r );
T e m p = t e m p-> n e x T;
}
R e t u r N;
}

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.