一、顺序表
#include<stdio.h>
#include<malloc.h>
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef struct
{
char *elem;
int length;
int listsize;
}SqList;
bool InitList_Sq(SqList &L)
{
L.elem = (char*)malloc(LIST_INIT_SIZE*sizeof(char));
if(L.elem==NULL)
{
return false;
}
L.length = 0;
L.listsize = LIST_INIT_SIZE;
return true;
}
bool ListInsert_Sq(SqList &L, int index, char e)
{
if(index<0 || index>L.length)
return false;
if(L.length>=L.listsize)
{
char *newbase = (char*)realloc(L.elem, (L.listsize + LISTINCREMENT)*sizeof(char));
if(newbase==NULL)
{
return false;
}
L.elem = newbase;
L.listsize += LISTINCREMENT;
}
char *q = &(L.elem[index]);
for(char *p = &(L.elem[L.length-1]); p>=q; --p)
{
*(p+1) = *p;
}
*q = e;
L.length++;
return true;
}
bool GetElem_Sq(SqList L, int index, char &e)
{
if(index<0 || index>=L.length)
return false;
e = L.elem[index];
return true;
}
bool ListDelete_Sq(SqList &L, int index)
{
if(index<0 || index>=L.length)
return false;
char *q = L.elem + L.length - 1;
for(char *p = &(L.elem[index]); p <= q-1; ++p)
{
*p = *(p+1);
}
L.length--;
return true;
}
void Print_Sq(SqList L)
{
char *p = L.elem;
for(int i=0; i!=L.length; i++)
{
printf("%c", *(p+i));
}
printf("\n");
}
int main()
{
SqList theList;
if(InitList_Sq(theList))
{
printf("Initial OK!");
ListInsert_Sq(theList,0,'a');
Print_Sq(theList);
ListInsert_Sq(theList,1,'b');
Print_Sq(theList);
ListInsert_Sq(theList,0,'c');
Print_Sq(theList);
ListDelete_Sq(theList,1);
Print_Sq(theList);
}
else
{
printf("Initial ERROR!\n");
}
getchar();
return 0;
}
二、单链表
#include <iostream>
using namespace std;
typedef struct LNode
{
char data;
struct LNode *next;
}LNode, *LinkList;
// 说明:逆位序输入 n 个元素的值,在 L 处建立带头结点的单链表
bool CreateList(LinkList &L, int n)
{
// 建立单链表的头结点
L = (LinkList)malloc(sizeof (LNode));
if (L == NULL)
return false;
L -> next = NULL;
for (int i = 0; i < n; ++i)
{
LinkList p = (LinkList)malloc(sizeof (LNode));
char data;
scanf("%c",&data);
p->data = data;
p->next = L->next;
L->next = p;
}
return true;
}// CreateList
// 说明:在带头结点的单链表 L 插入元素 c ,使其成为位序为 i 的元素,位序从 0 开始
bool ListInsert(LinkList &L, int i, char c)
{
LinkList p = L;
for (int index = 0; index < i; ++index)
{
if(p->next != NULL)
p = p->next;
else
return false;
}
LinkList newEle = (LinkList)malloc(sizeof (LNode));
newEle->data = c;
newEle->next = p->next;
p->next = newEle;
return true;
}
// 说明:逆序带头结点的单链表 L
bool ListReverse(LinkList &L)
{
if(L == NULL)
return false;
else
{
if(L->next == NULL)
{
return true;
}
else
{
// 核心代码
LinkList p, q, s; // 三个指针
p = L;
q = L->next;
while(q != NULL)
{
s = q->next;
q->next = p;
p = q;
q = s;
}
L->next->next = NULL;
L->next = p;
return true;
}
}
}
// 说明:顺序打印单链表 L
void PrintList(LinkList &L)
{
LinkList p = L->next;
while(p != NULL)
{
char tmp = p->data;
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main()
{
LinkList L;
CreateList(L, 3);
PrintList(L);
ListInsert(L, 1, '6');
PrintList(L);
ListReverse(L);
PrintList(L);
}