Data Structure-Insert elements to a linear table

Source: Internet
Author: User

# Include <iostream>
 
Using namespace std;
 
# Define LIST_INIT_SIZE 100 // initialize the allocation volume
 
# Define LISTINCREMENT 10 // increment of storage space allocation
 
 
Typedef int Status;
 
Typedef int ElemType;
 
Typedef struct {
 
ElemType * elem; // The base address of the bucket.
 
Int length; // The current length.
 
Int listsize; // The current allocated storage capacity (in sizeof (ElemType)
} SqList;
 
Status InitList_sq (SqList & L ){
 
L. elem = (ElemType *) malloc (LIST_INIT_SIZE * sizeof (ElemType ));
 
If (! L. elem) exit (1); // storage allocation failed
 
L. length = 0; // The length of the empty table is 0.
 
L. listsize = LIST_INIT_SIZE; // initial storage capacity
 
Return true;
}
Status ListInsert_Sq (SqList & L, int I, ElemType e)
{
// Insert a new element e before position I in the ordered linear table L
// The valid value of I is 1 <= I <= ListLength_Sq (L) + 1
If (I <1 | I> L. length + 1)
Return false; // The I value is invalid.
If (L. length> = L. listsize) // The current bucket is full and the allocation is increased.
{
ElemType * newbase = (ElemType *) realloc (L. elem, (L. listsize + LISTINCREMENT) * sizeof (ElemType ));
If (! Newbase)
Exit (1); // storage allocation failed
L. elem = newbase; // new base address
L. listsize + = LISTINCREMENT; // increase the storage capacity
}

ElemType * q = & (L. elem [I-1]); // q is the insert position

For (ElemType * p = & (L. elem [L. length-1]); p> = q; -- p)
* (P + 1) = * p; // right shift of the inserted position and subsequent elements

* Q = e; // insert e
+ L. length; // The table length increases by 1.
Return true;
}

Int main ()
{
SqList L;
InitList_sq (L );
ListInsert_Sq (L, 1, 2 );
Return 0;
}

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.