源码:
#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct Node{
ElemType data;
struct Node *next;
}Node,*LinkList;
bool InitList(LinkList &L){
L = (Node *) malloc(sizeof(Node));
if (L == NULL) {
return false;
}
L->next = NULL;
return true;
}
bool Empty(LinkList &L){
if (L->next == NULL) {
return true;
} else {
return false;
}
}
bool ListInsert(LinkList &L,int i,int e){
if (i < 1) {
return false;
}
Node *p;
p = L;
int j = 0;
while (p != NULL && j < i - 1) {
p = p->next;
j++;
}
if (p==NULL) {
return false;
}
Node *s = (Node *) malloc(sizeof(Node));
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
bool InsertNextNode(Node *p, int e){
if (p == NULL) {
return false;
}
Node *s = (Node *)malloc(sizeof(Node));
if (s == NULL) {
return false;
}
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
bool InsertPriorNode(Node *p, int e){
if (p == NULL) {
return false;
}
Node *s = (Node *) malloc(sizeof(Node));
if (s == NULL) {
return false;
}
s->next=p->next;
p->next = s;
s->data = p->data;
p->data = e;
return true;
}
bool InsertPriorNode(Node *p, Node *s){
if (p == NULL || s == NULL) {
return false;
}
s->next = p->next;
p->next = s;
int temp = p->data;
p->data = s->data;
s->data = temp;
return true;
}
bool DeleteNode(LinkList &L, int i, int &e){
if (i < 1) {
return false;
}
Node *p;
Node *q;
int j = 0;
p = L;
while (p != NULL && j < i - 1) {
p = p->next;
j++;
}
if (p == NULL) {
return false;
}
if (p->next == NULL) {
return false;
}
q = p->next;
e = q->data;
p->next = q->next;
free(q);
return true;
}
bool DeleteNode(Node *p){
if (p == NULL) {
return false;
}
Node *q = p->next;
if (q == NULL) {
return false;
}
p->data = q->data;
p->next = q->next;
free(q);
return true;
}
void DisplayList(LinkList L){
Node *p;
p = L->next;
int i = 0;
while (p != NULL) {
printf("%d", p->data);
p = p->next;
i++;
}
printf("\n");
printf("一共有%d个元素\n", i);
}
Node *GetElem(LinkList L, int i){
int j = 1;
Node *p = L->next;
if (i == 0) {
return L;
}
if (i < 1) {
return NULL;
}
while (p != NULL && j < i) {
p = p->next;
j++;
}
return p;
}
Node *LocateElem(LinkList L, ElemType e){
Node *p = L->next;
while (p != NULL && p->data != e) {
p = p->next;
}
return p;
}