算法设计:编程实现单链表基本操作,例如,创建结构,插入结点,删除结点等等。
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define TRUE 1;
#define FALSE 0;
#define OK 1;
#define ERROR 0;
#define INFEASIBLE - 1;
typedef int Status;
typedef int ElemType;
typedef struct LList {
ElemType elem;
struct LList* next;
}LList;
LList InitList_L(int size) {
LList *head=NULL;
LList *p = (LList*)malloc(sizeof(LList));
head = p;
p->elem = 0;
p->next = NULL;
for (int i = 0; i < size; i++) {
LList* temp = (LList*)malloc(sizeof(LList));
p->next = temp;
p = temp;
p->elem = i + 1;
p->next = NULL;
}
return *head;
}
Status GetElem_L(LList& L, int loc, ElemType& e) {
int i;
LList *temp=&L;
for (i = 1; i < loc; i++) {
temp = temp->next;
}
e = temp->elem;
return OK;
}
LList ListDelete_L(LList& L, int loc, ElemType& e) {
int i;
LList* temp = &L;
LList* head = &L;
if (loc == 1) {
head = L.next;
free(temp);
return *head;
}
for (i = 1; i < loc-1; i++) {
temp = temp->next;
}
LList* p = temp->next;
temp->next = p->next;
e = p->elem;
free(p);
return *head;
}
LList InsertElem_L(LList& L, int loc, ElemType e) {
int i;
LList* temp = &L;
LList* head = &L;
LList* p = (LList*)malloc(sizeof(LList));
p->elem = e;
if (loc == 1) {
head = p;
p->next = temp;
return *head;
}
for (i = 1; i < loc - 2; i++) {
temp = temp->next;
}
p->next = temp->next;
temp->next = p;
return *head;
}
Status Print_L(LList& L) {
LList* temp = &L;
cout << "out the table:";
while (!(temp->next == NULL)) {
cout << temp->elem << ' ';
temp = temp->next;
}
cout << endl;
return OK;
}
int main() {
LList A;
A.elem = 0;
A.next = NULL;
ElemType i;
A = InitList_L(10);
cout << "first table\n";
Print_L(A);
A = ListDelete_L(A, 5, i);
cout << "del the num " << i << " so the table is:\n";
Print_L(A);
A = InsertElem_L(A, 5, i+2);
cout << "add the num " << i+2 << " so the table is:\n";
Print_L(A);
return 0;
}