Sequential storage structure of linear table (C-language dynamic array implementation)

Source: Internet
Author: User

definition of a linear table: A finite sequence of n data elements

Linear tables are categorized from storage structures: sequential storage structures (arrays) and chained storage structures (linked lists)

Sequential storage structure: a contiguous memory space is used to store the data in the table l= (a1,a2,a3....an)

Chained storage structure: a contiguous memory space is used to store data for each row in the table, and segments are connected to each other by a reference (pointer) to form a chain-like storage structure

Seeing the diagram of the sequential storage structure, we might immediately associate the C language array. Yes, arrays are a typical sequential storage data structure. Below I pass an example, realizes to the sequential storage structure the data increment, the deletion, the change, the check operation.

First, a sequential storage structure describing the linear table data is set:

Default growth factor # default_capacity 10typedef unsigned int * pu32;typedef unsigned int u32;/****************************** * Linear table data structure, storing array elements, array size, array growth factor, hereinafter referred to as dynamic array           *//********************* /typedef struct _TAG_ARRAYLIST{PU32 container;//container int that stores array elements length;//array length int capacity;//array growth factor} tarraylist;
Container: is an unsigned 32-bit array of pointers used to store all the elements in a linear table, followed by the increment, delete, and change is the operation of the pointer element

Length: records the number of tuples in the array, indicating how many data elements are stored in the linear table

capacity: due to the function of dynamic expansion of the array, this value represents the size of each expansion after the array is full, default 10


Linear table Initialization
ArrayList * Arraylist_createdefault () {return arraylist_create (default_capacity);} ArrayList * arraylist_create (int capacity) {if (capacity < 0) {printf ("Fun arraylist_create error, illegal capacity:%d" , capacity); return NULL;} Tarraylist *list = (tarraylist *) malloc (sizeof (tarraylist)), if (list = = NULL) {printf ("Out of memory, create ArrayList fail !"); return NULL;} list->capacity = Capacity;list->length = 0;list->container = (PU32) malloc (sizeof (PU32) * default_capacity); (List->container = = NULL) {printf ("Out of memory, create Array container fail!"); return NULL;} memset (list->container, 0, sizeof (PU32) * default_capacity); return list;}

Arraylist_createdefault: Initialize the default 10 element size linear table storage space

Arraylist_create: Class based on capacity size

The ArrayList is a type defined by typedef void, because to block the internal implementation of linear table data storage structure, the user does not need to pay attention to the implementation details inside, only need to save the linear table handle reference, when each operation of the linear table, The handle is passed as a form to the corresponding function.


Adding elements to the specified position in a linear table

int Arraylist_additem (ArrayList *list, Arrayitem *item, int pos) {int ret = 0;  Tarraylist *arraylist = null;if (list = = NULL | | item = = NULL) {ret = -1;printf ("Fun arraylist_additem error:%d of the list is NULL or item is null\n ", ret); return ret;} ArrayList = (tarraylist *) list;//fault tolerant processing, assuming that 3 elements are currently stored, to insert an element in the 5th position, change the insertion position to the 4th position//|0|1|2|3| | |if (pos > arraylist-> Length) {pos = arraylist->length;} Expansion PU32 Newcontainer = null;if (arraylist->length > 0 && arraylist->length% arraylist->capacity = = 0) {Newcontainer = (PU32) malloc (sizeof (PU32) * (Arraylist->length + arraylist->capacity)); if (Newcontainer = = NULL {ret = -2;printf ("Out of memory, add Item fail!"); return ret;} memset (newcontainer, 0, Arraylist->length * sizeof (PU32));//copy old data into new container memcpy (Newcontainer, arraylist-> container, Arraylist->length * sizeof (PU32));//Release the memory of the old container free (arraylist->container);//Address to the new container arraylist-> container = Newcontainer;} Inserts an element into the array pos position for (int i = Arraylist->lEngth; i > pos; i--) {Arraylist->container[i] = arraylist->container[i-1];} Arraylist->container[pos] = (U32) item;arraylist->length++;return ret;}
1, before the addition, first infer that after adding an element, the array will be full, assuming that it will be full first expansion

Arraylist->length > 0 && arraylist->length% arraylist->capacity = = 0

2. Insert the element into the specified position in the array. Assuming that there are 5 elements in the current array, the new element is inserted into the 3rd position of the array, so the 3rd position and the subsequent elements are moved backwards

for (int i = arraylist->length; i > pos; i--)
{
Arraylist->container[i] = arraylist->container[i-1];
}
Arraylist->container[pos] = (U32) item;
arraylist->length++; //Length +1



Delete the element at the specified position in the linear table (opposite to join)

Arrayitem * Arraylist_removeitem (ArrayList *list, int pos) {tarraylist *arraylist = NULL; Arrayitem *arrayitem = null;arraylist = Checkrange (list, POS); if (arrayList = = null) {return null;} Cache deleted Element Arrayitem = (Arrayitem *) arraylist->container[pos];//removes the element from the array for the specified index for (int i = pos; i < Arraylist->len Gth i++) {Arraylist->container[i] = arraylist->container[i + 1];} arraylist->length--;//length minus 1return arrayitem;//returns the deleted element}
first save the element to be deleted before deleting it returns the element returned

There are other operations ( add elements at the end of the table, get, traverse, clear, destroy , etc.), here does not explain, the source of the specific gaze, the following gives the complete source code and test example:

arraylist.h//Linear Table Storage--dynamic array////Created by Yang Xin on 14-5-15.//Copyright (c) 2014 yangxin. All rights reserved.//#ifndef __arraylist_h__#define __arraylist_h__#ifdef _cplusplusextern "C" {#endiftypedef void arraylist;//linear table handle typedef void ARRAYITEM;//Linear table entry/* callback function for traversal array @item: Current element @pos: Index of current element */typedef void (*_each_function) ( Arrayitem *item, int pos);/* Creates a dynamic array of the default capacity size capacity 10@return dynamic array handle */arraylist * Arraylist_createdefault () ;/* Create a dynamic array with an initial capacity of capacity size @capacity: Array size growth factor, assuming the array is full, then self-growing capacity size @return dynamic array handle */arraylist * arraylist_ Create (int capacity);/* Add (Insert) an element at the specified location @list: Dynamic array handle @item: Newly added array element @pos: Insert position (Index starting from 0) @return insert successfully returns 0, failure returns non 0 value */int Arraylist_additem (ArrayList *list, Arrayitem *item, int pos);/* Add an element to the end of the array @list: Dynamic array handle @item: The newly added array element @return insert successfully returns 0, The failure returns a non-0 value */int arraylist_additemback (ArrayList *list, Arrayitem *item);/* Delete an array element @list: Dynamic array handle @pos: Insert position (index starting from 0) @return Delete successfully returned the deleted element, failed to return Null*/arrayitem * Arraylist_removeitem (ArrayList *list, int pos);* Empty array all elements @list: Dynamic array handle @return successfully returned 0, failed to return non 0 value */int arraylist_clear (ArrayList *list);/* Change array element @list: Dynamic array handle @item: New element @pos: Change element index @return change successfully returned 0, failed to return non 0 value */int arraylist_setitem (ArrayList *list, Arrayitem *item, int pos);/* Gets the element at the specified position of the array @list: Dynamic array handle @pos: Element index @return Returns the element at the specified position of the array, assuming that the POS is greater than or equal to the array length or less than 0, returns Null*/arrayitem * Arraylist_getitem ( ArrayList *list, int pos);/* Iterate array @list: Dynamic array handle @_fun_callback: callback function prototype when traversing each element of an array: void (*_each_function) (Arrayitem * Item, int pos); demo example: void Arrayeachcallback (Arrayitem *item, int pos) {...} */void Arraylist_for_each (ArrayList *list, _each_function _fun_callback);/* Iterate over the elements in the specified range of the array @list: Dynamic array handle @begin: Element start position @end: element End position @_fun_callback: callback function prototype when traversing each element of an array: void (*_each_function) (Arrayitem *item, int pos); Demo sample: void Arrayeachcallback (arrayitem *item, int pos) {...} */void Arraylist_for_each_range (ArrayList *list, int begin, int end,_each_function _fun_callback);/* Gets the length of the dynamic array (number of elements stored) @list: Dynamic array handle @return array length */int arraylist_getlength (ArrayList * list);/* Get dynamicArray growth factor @list: Dynamic array handle @return array growth factor */int arraylist_getcapacity (ArrayList * list);/* Destroy dynamic Array (free memory) @list: Dynamic array handle @return  Destroy successfully returned 0, failed to return non 0 value */int arraylist_destory (ArrayList **list); #ifdef _cplusplus} #endif #endif////arraylist.c// Linear table Storage--dynamic array////Created by Yang Xin on 14-5-15.//Copyright (c) 2014 yangxin. All rights reserved.//#include <stdio.h> #include <stdlib.h> #include <string.h> #include " ArrayList.h "//Default growth Factor # define default_capacity 10typedef unsigned int * pu32;typedef unsigned int u32;/****************** * Linear table data structure, storing array elements, array size, array growth factor, hereinafter referred to as dynamic array *//************** /typedef struct _TAG_ARRAYLIST{PU32 container;// Container for storing array elements int length;//array length int capacity;//array growth factor} tarraylist;//Check index range static Tarraylist * Checkrange (ArrayList *list, in t POS); ArrayList * Arraylist_createdefault () {return arraylist_create (default_capacity);} ArrayList * Arraylist_create (int CApacity) {if (capacity < 0) {printf ("Fun arraylist_create error, illegal capacity:%d", capacity); return NULL;} Tarraylist *list = (tarraylist *) malloc (sizeof (tarraylist)), if (list = = NULL) {printf ("Out of memory, create ArrayList fail !"); return NULL;} list->capacity = Capacity;list->length = 0;list->container = (PU32) malloc (sizeof (PU32) * default_capacity); (List->container = = NULL) {printf ("Out of memory, create Array container fail!"); return NULL;} memset (list->container, 0, sizeof (PU32) * default_capacity); return list;} int Arraylist_additem (ArrayList *list, Arrayitem *item, int pos) {int ret = 0;  Tarraylist *arraylist = null;if (list = = NULL | | item = = NULL) {ret = -1;printf ("Fun arraylist_additem error:%d of the list is NULL or item is null\n ", ret); return ret;} ArrayList = (tarraylist *) list;//fault tolerant processing, assuming that 3 elements are currently stored, to insert an element in the 5th position, change the insertion position to the 4th position//|0|1|2|3| | |if (pos > arraylist-> Length) {pos = arraylist->length;} Expansion PU32 Newcontainer = null;if (Arraylist->length >0 && arraylist->length% arraylist->capacity = = 0) {Newcontainer = (PU32) malloc (sizeof (PU32) * (arraylist-& Gt;length + arraylist->capacity)); if (Newcontainer = = NULL) {ret = -2;printf ("Out of memory, add Item fail!"); return ret;} memset (newcontainer, 0, Arraylist->length * sizeof (PU32));//copy old data into new container memcpy (Newcontainer, arraylist-> container, Arraylist->length * sizeof (PU32));//Release the memory of the old container free (arraylist->container);//Address to the new container arraylist-> container = Newcontainer;} Inserts an element into the array pos position for (int i = arraylist->length; i > pos; i--) {Arraylist->container[i] = arraylist->container[ I-1];} Arraylist->container[pos] = (U32) item;arraylist->length++;//length +1return ret;} int Arraylist_additemback (ArrayList *list, Arrayitem *item) {int ret = 0;  Tarraylist *arraylist = null;if (list = = NULL | | item = = NULL) {ret = -1;printf ("Fun Arraylist_additemback error:%d, of the List or item is null.\n "); return ret;} ArrayList = (tarraylist *) List;return Arraylist_additem (list, item, arraylist->length);} Arrayitem * Arraylist_removeitem (ArrayList *list, int pos) {tarraylist *arraylist = NULL; Arrayitem *arrayitem = null;arraylist = Checkrange (list, POS); if (arrayList = = null) {return null;} Cache deleted Element Arrayitem = (Arrayitem *) arraylist->container[pos];//removes the element from the array for the specified index for (int i = pos; i < Arraylist->len Gth i++) {Arraylist->container[i] = arraylist->container[i + 1];} arraylist->length--;//length minus 1return arrayitem;//returns the deleted element}int arraylist_clear (arrayList *list) {int ret = 0; Tarraylist *arraylist = null;if (list = = NULL) {ret = -1;printf ("Fun arraylist_clear error:%d, of the list is null.\n"); ret URN ret;} ArrayList = (Tarraylist *) List;while (arraylist->length) {arraylist->container[--arraylist->length] = 0;} return 0;} int Arraylist_setitem (ArrayList *list, Arrayitem *item, int pos) {int ret = 0;  Tarraylist *arraylist = null;arraylist = Checkrange (list, POS); if (arrayList = = NULL | | item = = NULL) {ret = -1;printf ("Fun Arraylist_setitem error:%d,of the list or item is null.\n ", ret); return ret;} Arraylist->container[pos] = (U32) Item;return 0;}  Arrayitem * Arraylist_getitem (ArrayList *list, int pos) {tarraylist *arraylist = Null;arraylist = Checkrange (list, POS); if (arrayList = = NULL) {return NULL;} Return (Arrayitem *) Arraylist->container[pos];} void Arraylist_for_each (ArrayList *list, _each_function _fun_callback) {tarraylist *arraylist = null;if (list = = NULL | | _f Un_callback = = NULL) {printf ("Fun Arraylist_for_each error, list or _fun_callback is null.\n"); return;} ArrayList = (Tarraylist *) list;for (int i = 0; i < arraylist->length; i++) {_fun_callback ((Arrayitem *) arraylist-> Container[i], i);}; void Arraylist_for_each_range (ArrayList *list, int begin, int end, _each_function _fun_callback) {tarraylist *arraylist = Null;if (list = = NULL | | _fun_callback = = NULL) {printf ("Fun arraylist_for_each_range error, list or _fun_callback is null. \ n "); return;} ArrayList = (Tarraylist *) list;if ((Begin < 0 | | begin > End) | | (End >= Arraylist->length | | End < Begin) {printf ("Arraylist_for_each_range error, pos out range:%d-%d", begin, end); return;} for (int i = begin; I < end; i++) {_fun_callback ((Arrayitem *) arraylist->container[i], i);}}; int arraylist_getlength (ArrayList * list) {tarraylist *arraylist = null;if (list = = NULL) {printf ("Fun arraylist_getlength Error, List is null.\n "); return-1;} ArrayList = (tarraylist *) List;return arraylist->length;} int arraylist_getcapacity (ArrayList * list) {tarraylist *arraylist = null;if (list = = NULL) {printf ("Fun arraylist_ Getcapacity error, List is null.\n "); return-1;} ArrayList = (tarraylist *) List;return arraylist->capacity;}  int arraylist_destory (ArrayList **list) {int ret = 0;if (list = = NULL) {ret = -1;printf ("Fun arraylist_destory error:%d from (List = = NULL) \ n ", ret); return ret;} Tarraylist *arraylist = (tarraylist *) *list;if (Arraylist->container! = NULL) {free (arraylist->container); Arraylist->container = NULL;} Free (arrayList); *list =Null;return ret;} Static Tarraylist * Checkrange (ArrayList *list, int pos) {tarraylist *arraylist = null;if (list = = NULL) {printf ("Fun Checkr Ange error, the list is null.\n "); return NULL;} ArrayList = (Tarraylist *) list;if (pos < 0 | | pos >= arraylist->length) {printf ("Fun checkrange error, of the POS: %d out range.\n ", POS); return NULL;} return arrayList;} -------------------------Test Example--------------------------------//#include <stdio.h> #include <stdlib.h > #include "ArrayList.h" typedef struct PERSON {int Age;char name[20];} Person;void Eacharraycallback (arrayitem *item, int pos) {Person *p = (person *) item;printf ("%d-->age=%d\n", pos,p- >age);} void Main1 () {int ret =-65535; ArrayList *list = Null;list = Arraylist_create (2); Person P1, p2, p3, p4, p5,p6,p7,p8;p1.age = 10;p2.age = 20;p3.age = 30;p4.age = 40;p5.age = 50;p6.age = 60;p7.age = 70;p8. Age = 80;//arraylist_additem (list, 100, 7); Arraylist_additem (list, &AMP;P1, 0); Arraylist_additem (list, &p2, 0); Arraylist_aDditem (list, &p3, 0); Arraylist_additem (list, &AMP;P4, 0); Arraylist_additem (list, &AMP;P5, 0); Arraylist_additem (list, &AMP;P6, 0); Arraylist_additemback (list, &AMP;P7); Arraylist_additemback (list, &AMP;P8);p rintf ("Array length:%d\n", Arraylist_getlength (list));  Arrayitem *item = Arraylist_removeitem (list, 2);p rintf ("delete element at index 2:%d\n", ((person *) item)->age); for (int i = 0; i < Arraylist_getlength (list); i++) {Person *p = (person *) Arraylist_getitem (list, i);p rintf ("age=%d\n", P->age);} Person pp = {, "Zhangsan"}; Arraylist_setitem (list, &pp, 1);//change the element with index position 1 person *p = (person *) Arraylist_getitem (list,1); if (P! = NULL) {printf ( "age=%d\n", P->age);} printf ("\ n---------------------the foreach callback function to traverse the array------------------\ n"); Arraylist_for_each (list, eacharraycallback);//Iterate over the specified range of elements printf ("\ N---------------foreach iterates over the array element within the specified range------------------\ n "); Arraylist_for_each_range (list, 2, 5, eacharraycallback);//Qingxu array all elements ret = arraylist_clear (list);p rintf ("ArrayList Length:%d\n ", arraylist_getlength(list)); ret = Arraylist_destory (&list); System ("Pause");} void Fun (Arrayitem *item, int pos) {printf ("%d--%d\n", POS, (unsigned int) item);} void Main () {ArrayList *list = Null;list = Arraylist_create (5); Arraylist_additem (list, (Arrayitem *) 10, 0); Arraylist_additem (list, (Arrayitem *) 20, 0); Arraylist_additem (list, (Arrayitem *) 30, 0); Arraylist_additem (list, (Arrayitem *) 40, 0); Arraylist_additem (list, (Arrayitem *) 50, 0); Arraylist_additemback (list, (Arrayitem *));p rintf ("delete-->%d\n", (unsigned int) arraylist_removeitem (list, 0) ); Arraylist_for_each (list, fun); Arraylist_destory (&list); System ("Pause");}

Sequential storage structure of linear tables (C-language dynamic array implementations)

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.