链表的基本操作
#include <iostream>
#include <stdlib.h>
using namespace std;
typedef struct listNode
{
int date;
struct listNode* next;
}listNode;
listNode* Creat_head(listNode* head)
{
head = (listNode*)malloc(sizeof(listNode));
if(!head) exit(0);
head->next = NULL;
listNode* pr = head;
char ch = ' ';
while(ch == ' ')
{
int num;
cin >> num;
ch = getchar();
listNode* p = (listNode*)malloc(sizeof(listNode));
if(!p) exit(0);
p->date = num;
p->next = head->next;
head->next = p;
}
return head;
}
listNode* Creat_tail(listNode* head)
{
if(!head)
{
head = (listNode*)malloc(sizeof(listNode));
if(!head) exit(0);
head->next = NULL;
}
listNode* p = head;
char ch = ' ';
while(ch == ' ')
{
int num;
cin >> num;
ch = getchar();
listNode* temp = (listNode*)malloc(sizeof(listNode));
if(!temp) exit(0);
temp->next = NULL;
temp->date = num;
p->next = temp;
p = p->next;
}
return head;
}
void printData(listNode* head)
{
listNode *p = head->next;
while(p)
{
cout << p->date << " ";
p = p->next;
}
putchar('\n');
}
int DelletANode(listNode* head,int e)
{
listNode* p = head->next;
listNode* pr = head;
while(p)
{
if(p->date == e)
{
listNode* temp = p;
pr->next = p->next;
free(p);
return 1;
}
pr = p;
p = p->next;
}
return 0;
}
listNode* InsertTail(listNode* head,int num)
{
if(!head)
{
head = (listNode*)malloc(sizeof(listNode));
if(!head) exit(0);
head->next = NULL;
}
listNode* pr = head;
listNode* p = (listNode*)malloc(sizeof(listNode));
if(!p) exit(0);
p->date = num;
p->next = NULL;
while(pr->next) pr = pr->next;
pr->next = p;
return head;
}
listNode* InsertHead(listNode* head,int num)
{
if(!head)
{
head = (listNode*)malloc(sizeof(listNode));
if(!head) exit(0);
head->next = NULL;
}
listNode* p = (listNode*)malloc(sizeof(listNode));
if(!p) exit(0);
p->date = num;
p->next = head->next;
head->next = p;
}
void DestroyList(listNode* head)
{
listNode* p = NULL;
while(head)
{
p = head;
head = head->next;
free(p);
}
}
int main()
{
listNode* head = NULL;
head = Creat_tail(head);
printData(head);
InsertTail(head,100);
printData(head);
}
顺序表的基本操作
#define MAXSIZE 100
typedef struct sqlist
{
int* elem;
int length;
int listsize;
}sqlist;
void Creat_list(sqlist* sq)
{
sq->elem = (int*)malloc(MAXSIZE * sizeof(int));
sq->length = 0;
sq->listsize = MAXSIZE;
}
void Insert_sqlistTail(sqlist* sq,int e)
{
if(sq->length >= sq->listsize)
{
int *p = (int*)realloc(sq->elem,(sq->listsize + MAXSIZE) * sizeof(int));
sq->elem = p;
sq->listsize += MAXSIZE;
}
sq->elem[sq->length] = e;
sq->length ++;
}
void Insert_sqlistHead(sqlist* sq,int e)
{
int i;
if(sq->length >= sq->listsize)
{
int *p = (int*)realloc(sq->elem,(sq->listsize + MAXSIZE) * sizeof(int));
sq->elem = p;
sq->listsize += MAXSIZE;
}
for(i = sq->length - 1;i > 0;i --)
{
sq->elem[i] = sq->elem[i-1];
}
sq->elem[0] = e;
sq->length ++;
}