The C code of a single linked list

Source: Internet
Author: User

We know that data structures are information and their interrelationships, including logical and physical structures. The logical structure of a single-linked list is a one-to linear relationship, the physical structure is the use of nodes to combine data, in the computer to reflect such a-to-one data relationship. A single-linked list node consists of a data field containing information about the data itself and a pointer field that embodies the data-to-one relationship. Because the single-linked list has only one pointer to the back node, the next so that the single-linked list can only be traversed from the back, but not from the back, which means that once a single-linked list of a node is lost, all the data information will be lost, and the single-linked list has a head pointer is unique, to find the single
A data can only be traversed from the beginning, the worst time complexity is O (n), but because the data is a pointer to determine the relationship between the data, so the single-linked list in memory is not necessarily contiguous allocation of memory, can more efficient use of memory space, and can quickly insert and delete a data element after a node. The worst-case complexity of inserting and deleting a node after a node is O (1). When writing programs, especially process-oriented C language programs must keep in mind program = data structure + algorithm. There are two ways to store data in memory, one is to continuously store an array, and the other is a struct. The algorithm is the operation of the data. At the same time the data structure and the algorithm defined on the data structure constitute an abstract data type, note that here is the type, the type is not just the data, there are related algorithms defined in the data.

A single-linked list consists of n identical nodes, each of which contains two information, a data field containing data information, and a pointer field that contains the relationship between data so to declare a single-linked list struct, we must declare a node structure of a single-linked list node structure ListNode.

1. header File List.h

Single-linked list List.h#ifndef list_h#define list_h//single-linked list node data structure typedef struct LISTNODE{VOID * data;//because you don't know what data is stored in a single-linked list, For abstraction, use a generic pointer void* to point to the data ListNode *next;//pointer to the next node next}listnode;//can be related to a single linked list node (1) initialize a node with one data (2) to read the data information of the node (3) Destruction of a node//init_nodelistnode* init_node (void *data); The initialization of a node is finally generated by a node void *get_data (const listnode * list_node); void Destroy_node (ListNode * list_node);//single-linked list abstract type// Single-linked list data structure (1) The size of a single-linked list (2) head node Head (3) Tail node tail (4) Add a new node (5) Destroy node typedef struct LIST{INT size;//size ListNode *head;//head node pointer li Stnode *tail;//Tail node pointer listnode* (*init_node) (void *data);//Add a node int (*destroy_node) (ListNode *list_node);//Destroy a node} list;//for single-linked lists: (1) Initialize single-linked list init_list (2) Insert a new node after a node ins_next_list//(3) Delete a node after one node Rem_next_list (4) Destroy single-linked list Dstroy_  list//(5) Single-linked list size size_list (6) Gets the head node Head_list (7) Gets the tail node tail_list (8) determines whether the head node Is_head//Determines whether it is a tail node is_tailvoid init_list (list *list), int ins_next_list (list *list,listnode *now_node,int (*init_node) (void *data)), int rem_next_list (list *list, ListNode *now_node,int (*destroy_node) (ListNode *list_node)); void Destroy_list (list *list); int size_list (const list *list); listnode* head_list (const list *list); listnode* tail_list (const list *list), int is_head (const list *list), int is_tail (const list *list), #endif

2. Single-linked list implementation file List.cpp

list.cpp#include<stdlib.h> #include <stdio.h> #include "list.h"//Generate a single-linked list node: init_node//function: Dynamically allocating memory, Generates a single-linked list node, data in the data field, and null for a single-linked list./return value: Dynamically allocated single-linked list node pointer in memory listnode//time complexity: O (1) listnode* init_node (void *data {listnode* New_node;//Declare a pointer to a single-linked list node type//Allocate memory space for the new node in the heap if (New_node = (listnode*) malloc (sizeof (listnode))) = = NULL) r Eturn null;//allocation failure//assignment succeeded//encapsulates data as node New_node->data = Data;new_node->next = null;//Returns a pointer to the node return new_node;} Destroy_node: Frees the memory space held by the node List_node//return value: void//parameter; List_node is a single-linked list node//time complexity: O (1) void Destroy_node (ListNode * list_node) {free (list_node); return;} Initialize single-linked list init_list//function: After this initialization of the rest of the list, the compiler will error if Init_list is not called: List is not initialized. Return value void//time complexity O (1) void init_list (list *list) {list->size = 0;list->head = Null;list->tail = NULL;} Insert a new node in the list: ins_next_list//function: Insert a new node after a node Now_node data, and if Now_node is NULL then insert//return value in the head of the linked list: Insert fails when insert successfully returns 0 Return -1//time Complexity: O (1)//parameter: List is empty, list has only one node, list has multiple nodes, Now_node is empty, Now_node is intermediate node//now_node as tail node//test Case {List = = null, Now_node = = NULL, [1,2,3,4,5],now_node->next = = Null}int ins_next_list (list *list,listnode *now_node, void *data) {//encapsulates the data as a new node, where a dynamic allocation of memory space is required, and if (list = = NULL) is already encapsulated in int (*init_node)//(void *data) return-1;else{ ListNode *new_node = (*init_node) (data);//The Encapsulated node type//Inserts the node into the appropriate location//view the list of linked list which elements have changed//size self-increment if (Now_node = = NULL)// The new node is inserted as the head node {if (list->size = = 0)//When the list is empty {List->head = New_node;list->tail = new_node;++list->size;} else//the list is not empty, {New_node->next = List->head;list->head = new_node;++list->size;} You can extract the common code here//list->head = New_node;//++list->size;} New node non-head node (Now_node is the middle node, Now_node is the last second node in the list, Now_node is the last node) else{if (Now_node = = list->tail)//current node is tail node {new_ Node->next = Now_node->next;now_node->next = New_node;list->tail = new_node;++list->size;} else//The current node is the middle node {new_node->next = Now_node->next;now_node->next = new_node;++list->size;} Here you can extract the common code for the insertion node://New_node->next = now_node->next;//Now_node->next = New_node;} Inserts have a list length plus 1//++list->sziereturn 0;}} Rem_next_list: After deleting a node from the single-linked list current node Now_node, the list must already be initialized, and when the incoming argument now_node//Is null, the header node//function return value is deleted: When the delete succeeds returns 0 when the deletion fails back -1/ /Parameter Description: List must already be initialized, list cannot be empty, Now_node = = NULL to delete head node, Now_node for tail node, return -1,//int (*destroy_node) (ListNode *list_node); As a function pointer, a destructor that points to a node, which means that the memory space occupied by the node is dynamically freed in the heap. Time complexity: O (1)//test Case Description: 1.list uninitialized (return-1), 2.list to null 2.list only one node (Now_node = = NULL (delete head node, head =tail = Null,size =0), now _node = = Head (delete failed, return-1))//3.list has multiple nodes (Now_node = = NULL (delete head node, head =head->next), Now_node = = Head, Now_node = = Middle Node (pnode), (normal delete, 1. Save the original information 2. Release node memory space, 3.size-1)//now_node = penultimate node (delete tail node, normal delete outside, tail, size needs to change), Now_node =tail (delete failed, return-1)) int rem_next_list (list *list,listnode *now_node,void (*destroy_node) (ListNode *list_node)) {ListNode * old_ node;//the node to be deleted ListNode *pnode;//The middle node if (list = = NULL)//The linked list does not exist return-1;if (list->size = 0)//list is empty return-1;if ( List->size = = 1)//linked list only one node {if (Now_node = = NULL)//Delete head node {old_node = LIst->head;destroy_node (Old_node);//Destroy the node, release the memory space occupied by the node List->head = List->tail = null;//The list is empty--list->size; return 0;} else//delete failed return-1;} else if (list->size = = 2)//list consists of two nodes {if (Now_node = = NULL)//Delete head node {pnode = List->head->next;old_node = List->hea D;destroy_node (Old_node);//Destroy node List->head = List->tail = pnode;//The only remaining node after deletion, that is, the head node, and the tail node--list->size; return 0;} /*else if (now_node->next = list->tail) */else if (Now_node->next = = list->tail)//Delete tail node {now_node-n ext = list->tail->next;//Delete the tail node, you must make the previous node of the tail node point to Null;old_node = now_node->next;//the node to be deleted, that is, the tail node//pnode = Old_node->next;destroy_node (old_node); list->tail = list->head;//Only one node is left after deletion, and the tail node and head node are the same node. is the original head node--list->size;return 0;} else//Delete nonexistent node, failed {return-1;}} else//The list has n (n>2) nodes {if (Now_node = = NULL)//Delete head node {old_node = List->head;pnode = Old_node->next;destroy_node ( Old_node);//Destroy Node List->head = Pnode;--list->size;return (0);} else//Delete other Node {Old_node =Now_node->next;if (Old_node = = NULL)//delete the nonexistent node {return-1;} else if (Old_node = = list->tail)//Delete tail node {//now_node, next = null;//if the tail node is deleted note Be sure to point the pointer field of the previous node of the tail node next to the Nullnow_nod E-Next = old_node-Next;//pnode = Old_node->next;pnode = Now_node;destroy_node (old_node); list->tail = P Node;--list->size;return 0;} else//Delete the middle node {pnode = Old_node->next;now_node->next = pnode;//the node to be removed removes Destroy_node from the list (old_node);// The number of nodes that are freed up by the node's memory--list->size;//list -1return 0;}}} Destroy_list: Destroying a single-linked list, destroying the node of the linked list//return value from start to finish: Destroy successfully returns 0, destroy failure returns -1;//parameter: The single linked list already initialized//time complexity: O (n) is equivalent to traversing the entire single-linked list void destroy_list (List *list) {while (list->size > 0)//If the linked list is not empty, call the already defined function to remove the linked list node rem_next_list (List,null,destroy_node) from beginning to end;} int main (void) {list list;//declares a single-linked list *plist = &list;//Test initialization linked list: Init_list (&list) init_list (plist);//Initialize single-linked list at this time printf ("list_size:%d\n", Plist->size);p rintf ("list_head:%p\n", Plist->head);p rintf ("list_tail:%p\n", plist- >tail);//Tests Insert a node in the list: int ins_next_list (List *list,lIstnode *now_node, void *data)//test Data Set data{1,2,3,4,5}//test case [list,now_node,data]=[null,null,1]; [list,null,1]; [list,head,2]; [List, middle node, 3]//[list,null,0]; [List,tail,5]int data[5] ={1,2,3,4,5};int True = ins_next_list (null,null,&data[1]);//return value is-1 insert failed printf ("Ins_next _list:%d\n ", True); True = Ins_next_list (plist,null,&data[1]);//Add Head node data entry data =2, list_size = 1 elements in the linked list: {2}printf ("ins_next_list:%d\n ", True);p rintf (" list_size:%d\n ", Plist->size);p rintf (" *data:%d\n ", * (int*) (Plist->head->data)); True = Ins_next_list (plist,plist->head,&data[2]);//Add a node data item after the head node data=3, list_size = 2 data element {2,3}printf (") in the linked list Ins_next_list:%d\n ", True);p rintf (" list_size:%d\n ", Plist->size);p rintf (" *data:%d\n ", * (int*) (plist->head- >next->data)); True = Ins_next_list (plist,plist->head->next,&data[3]);//Add a node after the second node data item =4, List_size = 3, the data element in the linked list { 2,3,4}printf ("ins_next_list:%d\n", True);p rintf ("list_size:%d\n", Plist->size);p rintf ("*data:%d\n", * (int*) ( Plist->head->next-&gT;next->data)); True = Ins_next_list (plist,null,&data[0]);//Insert a node in front of the chain header node as the new head node, data item 1, data element in the linked list {1,2,3,4}printf ("Ins_next _list:%d\n ", True);p rintf (" list_size:%d\n ", Plist->size);p rintf (" *data:%d\n ", * (int*) (Plist->head->data) ); True = Ins_next_list (plist,plist->tail,&data[4]);//Add a node after the tail node as a new tail node, data item 5, data element in the linked list {1,2,3,4,5}printf ("ins_next_list:%d\n", True);p rintf ("list_size:%d\n", Plist->size);p rintf ("*data:%d\n", * (int*) (plist-> Tail->data));//The output list of all data elements (traversal) {1,2,3,4,5}listnode* Pnode = plist->head;while (pnode! = NULL) {printf ("%d", * ( int*) pnode->data);p node = Pnode->next;} printf ("\ n");////test destroy chain is represented in the list of data elements {1,2,3,4,5},//Destroy_list (plist);//printf ("plist->size:%d\n",plist-> size);//If the////test is successfully destroyed for the 0 linked list, delete the node in a linked list//Now the list has 5 total data to traverse the result to {1,2,3,4,5}//test case {The list is not initialized, the list is empty, the list has n (n=5) nodes (delete head node, Delete the tail node, delete the middle node) linked list only two nodes, linked list only one node}listnode* qnode;//test node list qlist; List *pqlist = &qlist;//test with the linked list int result; The result of the failure to determine whether to delete the node, result = 0, deleteSuccess, result =-1, delete failed//1. List not initialized, pass compiler syntax Check//qnode = Null;//result = Rem_next_list (pqlist,qnode,destroy_node);//// printf ("Rem_next_list:%d", result);//1. The list is empty, the deletion fails to return -1init_list (pqlist); qnode = Null;result = Rem_next_list (Pqlist, Qnode,destroy_node);//printf ("Rem_next_list:%d\n", result),//2. The list has 5 nodes, {1,2,3,4,5} delete the head node {2,3,4,5}pqlist = plist;    Qnode = Null;result = Rem_next_list (pqlist,qnode,destroy_node);p rintf ("Rem_next_list:%d\n", result); Pnode = Pqlist->head;while (pnode! = NULL) {printf ("%d", * (int*) pnode->data);p node = Pnode->next;} printf ("\ n");//delete the tail node in the linked list, delete the element in the linked list as {2,3,4};pqlist = plist;//find the tail node of the previous node Qnode = Pqlist->head;while (qnode->next! = Pqlist->tail) Qnode = qnode->next;//This removes the tail node 5result = rem_next_list (pqlist,qnode,destroy_node);p rintf ("Rem_    Next_list:%d\n ", result); Pnode = Pqlist->head;while (pnode! = NULL) {printf ("%d", * (int*) pnode->data);p node = Pnode->next;}   printf ("\ n");//At this time the linked table data {2,3,4}, delete the middle node 3 after the linked list data field {2,4}pqlist = plist; Find tail node previous node Qnode = pqlist->head;//this removes the tail node 3result = rem_next_list (pqlist,qnode,destroy_node);p rintf ("Rem_next_list:%d\n", result    ); Pnode = Pqlist->head;while (pnode! = NULL) {printf ("%d", * (int*) pnode->data);p node = Pnode->next;} printf ("\ n");//Only two nodes {2,4} After removing the head node 2, the linked list data is {4}pqlist = plist;//the node to be deleted Qnode = null;//At this point the head node of the 2 data is deleted; result = Rem_next_    List (Pqlist,qnode,destroy_node);p rintf ("Rem_next_list:%d\n", result); Pnode = Pqlist->head;while (pnode! = NULL) {printf ("%d", * (int*) pnode->data);p node = Pnode->next;} printf ("\ n");////only two nodes {2,4} After deleting the tail node 4, the linked list data is {2}//pqlist = plist;////the node to be deleted before node//qnode = pqlist->head;//// At this time, the head node of the 2 data is deleted;//result = Rem_next_list (Pqlist,qnode,destroy_node);//printf ("Rem_next_list:%d\n", result); Pnode = Pqlist->head;//while (pnode! = NULL) {//printf ("%d", * (int*) pnode->data);//pnode = pnode->next;//}/ /printf ("\ n");//Only two nodes {2,4}, the current node is the tail node//pqlist = plist;//printf ("Size:%d\n", pqlist->size),////current node for tail node deletion failed returns 1; The data is not changed after deletion or {2,4}//qnode = Pqlist->tail;////result = Rem_next_list (Pqlist,qnode,destroy_node);//printf ("Rem_next_list:%d\n", result); Pnode = Pqlist->head;//while (pnode! = NULL) {//printf ("%d", * (int*) pnode->data);//pnode = pnode->next;//}/ /printf ("\ n");//Only one node is left in the list {4},pqlist = plist;//the previous node to be deleted is head, the deletion fails to return 1; The list is still {4}qnode = pqlist->head; after the operation ends    result = Rem_next_list (Pqlist,qnode,destroy_node);p rintf ("Rem_next_list:%d\n", result); Pnode = Pqlist->head;while (pnode! = NULL) {printf ("%d", * (int*) pnode->data);p node = Pnode->next;} printf ("\ n");//The list is left with only one node data {4},pqlist = plist;//the passed-in parameter is null, the delete successfully returns 0, the linked list is empty after the operation ends, Qnode = Null;result = Rem_next_list (pql    Ist,qnode,destroy_node);p rintf ("Rem_next_list:%d\n", result);p rintf ("The list is empty, La La)"; Pnode = Pqlist->head;while (pnode! = NULL) {printf ("%d", * (int*) pnode->data);p node = Pnode->next;} printf ("\ n"); return 0;}
3. Test results:

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The C code of a single linked list

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.