本文讲的是各操作的代码实现
定义结点
typedef struct Node{
int data;
struct Node* pre;
struct Node* next;
}Node;
链表初始化(含头结点)
Node* initList() {
Node* L = (Node*)malloc(sizeof(Node));
L->data = 0;
L->next = L;
L->pre = L;
return L;
}
头插法
void headInsert(Node* L, int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->pre = L;
node->next = L->next;
//若此时的链表为空,则要将L的头指针指向node,否则不做改变
if (L->data == 0)
L->pre = node;
else {
L->next->pre = node;
}
L->next = node;
L->data++;
}
尾插法
void tailInsert(Node* L, int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
Node* n = L->next;
while (n->next != L) {
n = n->next;
}
n->next = node;
node->pre = n;
node->next = L;
L->pre = node;
L->data++;
}
删除结点
void delete(Node* L, int data) {
Node* n = L->next;
while (n->next != L) {
if (n->data == data) {
n->pre->next = n->next;
n->next->pre = n->pre;
L->data--;
break;
}
n = n->next;
}
}
打印列表
void printList(Node* L) {
Node* node = L->next;
while (node != L) {
printf("%d->", node->data);
node = node->next;
}
printf("以上%d个元素循环\n",L->data );
}
主函数(用于检验函数是否有效)
int main() {
Node* L = initList();
headInsert(L, 1);
headInsert(L, 2);
headInsert(L, 3);
headInsert(L, 4);
headInsert(L, 5);
printList(L);
tailInsert(L, 6);
tailInsert(L, 7);
tailInsert(L, 8);
printList(L);
delete(L, 4 );
delete(L, 7);
printList(L);
}
完整源代码
typedef struct Node{
int data;
struct Node* pre;
struct Node* next;
}Node;
Node* initList() {
Node* L = (Node*)malloc(sizeof(Node));
L->data = 0;
L->next = L;
L->pre = L;
return L;
}
void headInsert(Node* L, int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->pre = L;
node->next = L->next;
//若此时的链表为空,则要将L的头指针指向node,否则不做改变
if (L->data == 0)
L->pre = node;
else {
L->next->pre = node;
}
L->next = node;
L->data++;
}
void tailInsert(Node* L, int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
Node* n = L->next;
while (n->next != L) {
n = n->next;
}
n->next = node;
node->pre = n;
node->next = L;
L->pre = node;
L->data++;
}
void delete(Node* L, int data) {
Node* n = L->next;
while (n->next != L) {
if (n->data == data) {
n->pre->next = n->next;
n->next->pre = n->pre;
L->data--;
break;
}
n = n->next;
}
}
void printList(Node* L) {
Node* node = L->next;
while (node != L) {
printf("%d->", node->data);
node = node->next;
}
printf("以上%d个元素循环\n",L->data );
}
int main() {
Node* L = initList();
headInsert(L, 1);
headInsert(L, 2);
headInsert(L, 3);
headInsert(L, 4);
headInsert(L, 5);
printList(L);
tailInsert(L, 6);
tailInsert(L, 7);
tailInsert(L, 8);
printList(L);
delete(L, 4 );
delete(L, 7);
printList(L);
}