顺序表:顺序表是在计算机内存中以数组的形式保存的线性表,是以段内存连续的存储数据元素的现性结构,只要确定了起始位置的地址,后面的元素就会连续的存储在起始地址之后。
链表:链表是一种链式存取的数据结构,链式存储的的数据元素的地址在内存中是任意的。它的数据是以结点来存储的,还需要一个指针来将所有的结点连接起来。
单链表的代码如下:
typedef class Node
{
public:
int data;
Node *next;
}node;
class List
{
public:
List()
{
count = 0;
head = NULL;
}
~List()
{
}
Node *buyNode(int val,Node *next )
{
Node *p = new Node();
p->data = val;
p->next = next;
return p;
}
void insert(int pos,int val)
{
if (head == NULL)
{
head = buyNode(val, NULL);
count++;
return;
}
if (pos < 0 || pos >count)
{
cout << "pos is error!" << endl;
return;
}
Node *q = head;
if (pos == 0)
{
Node *p = buyNode(val, head);
head = p;
}
else
{
while (pos - 1 > 0)
{
q = q->next;
pos--;
}
Node *p = buyNode(val, q->next);
q->next = p;
}
count++;
}
void inserthead(int val)
{
insert(0, val);
}
void inserttail(int val)
{
insert(count, val);
}
void Delete(int pos)
{
if (pos < 0 || pos > count)
{
cout << "the pos is error!" << endl;
return;
}
Node *p = head;
Node *q = p->next;
if (pos == 0)
{
free(head);
head = q;
}
else
{
while (pos - 1 > 0)
{
p = p->next;
q = q->next;
pos--;
}
p->next = q->next;
free(q);
}
count--;
}
void Deletehead()
{
Delete(0);
}
void Deletetail()
{
Delete(count);
}
int length()
{
return count;
}
void show()
{
Node *p = head;
while (p!= NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
private:
int count;
Node *head;
};
int main()
{
List l;
for (int i = 0; i < 10; i++)
{
l.inserthead(i);
}
l.insert(0, 10);
cout << l.length() << endl;;
l.Delete(5);
cout << l.length() << endl;;
l.show();
return 0;
}
顺序表的代码如下:
class SXlist
{
public:
SXlist(int a = 10)
{
data = new int[10];
size = 10;
count = 0;
}
~SXlist()
{
}
void expand()
{
size = size + (size / 2);
int *p = new int[size];
for (int i = 0; i < count; i++)
{
p[i] = data[i];
}
free(data);
data = p;
}
bool isempty()
{
return count == 0;
}
bool isfull()
{
return count >= size;
}
void Insert(int val, int pos)
{
if (isfull())
{
expand();
}
if (pos < 0 || pos > count)
{
cout << "the pis is error" << endl;
}
for (int i = count; i > pos; i--)
{
data[i] = data[i - 1];
}
data[pos] = val;
count++;
}
void Inserthead(int val)
{
Insert(val, 0);
}
void Inserttail(int val)
{
Insert(val, count);
}
void Delete(int pos)
{
if (isempty())
{
return;
}
if (pos < 0 || pos > count)
{
cout << "the pos is error" << endl;
return;
}
for (int i = pos; i < count; i++)
{
data[i - 1] = data[i];
}
count--;
}
void show()
{
for (int i = 0; i < count; i++)
{
cout << data[i] << " ";
}
cout << endl;
}
int getcount()
{
return count;
}
private:
int *data;
int size; //能够存储的大小
int count; //已经存储的个数
};
int main()
{
SXlist s;
for (int i = 0; i < 16; i++)
{
s.Inserthead(i);
}
s.Inserthead(21);
s.Inserttail(23);
cout << s.getcount() << endl;
s.show();
s.Delete(5);
cout << s.getcount() << endl;
s.show();
}