C语言实现双链表插入和删除,判空,算长度,翻转
# include <stdio.h>
# include <stdlib.h>
typedef struct LNode {
int data;
struct LNode *prev;
struct LNode *next;
}Node, *NodeList;
// 初始化 带头结点
bool InitList(NodeList &L) {
L = (Node *)malloc(sizeof(Node));
if (L!=NULL) {
L->data = NULL;
L->prev = NULL;
L->next = NULL;
return true;
}else {
return false;
}
}
// 判断空表
bool EmptyList(NodeList &L) {
if (L->next==NULL) {
return true;
}else {
return false;
}
}
// 表长度
int Length(NodeList &L) {
Node *head = L->next;
int c = 0;
while (head!=NULL) {
head=head->next;
c++;
}
return c;
}
// 打印链表
void output(NodeList &L) {
Node *head = L->next;
while(head!=NULL) {
int ccc = head->data;
printf("%d -> ", ccc);
head=head->next;
}
}
// 反向打印验证
void fanzhuan(NodeList &L) {
// 找到尾结点
Node *head = L;
Node *end = L->next;
while(end!=NULL){
end=end->next;
head=head->next;
}
printf("\n尾结点: %d\n", head->data);
while(head->prev!=NULL){
printf("%d -> ", head->data);
head=head->prev;
}
}
// 在第k个位置插入e元素
bool addList(NodeList &L, int k, int e) {
if ((k<1)||(k>Length(L)+1)) {
return false;
}else {
// 申请节点空间
Node *cc = (Node *)malloc(sizeof(Node));
cc->data = e;
// 空表插入
if (EmptyList(L)) {
cc->prev = L;
cc->next = NULL;
L->next = cc;
}else {
// 遍历到前一节点
Node *head = L;
for(int i=0;i<k-1;i++){
head=head->next;
}
// 前指针
cc->prev = head;
// 是否是尾指针
if(head->next==NULL) {
// 后指针
cc->next = NULL;
// 前节点的后指针
head->next = cc;
return true;
} else {
// 后指针
cc->next = head->next;
// 后节点的前指针
head->next->prev = cc;
// 前节点的后指针
head->next = cc;
return true;
}
}
}
}
// 删除第k个位置的元素 e
bool DeleteList(NodeList &L, int k, int &e) {
// 判断合法
if ((k<1)||(k>Length(L))) {
return false;
}else {
// 空表情况
if (EmptyList(L)) {
return false;
}else {
Node *head = L;
for (int i=0;i<k-1;i++) {
head=head->next;
}
e = head->next->data;
// 如果是尾节点
if (head->next->next==NULL) {
// 释放这个空间
free(head->next);
// 前节点的后指针
head->next = NULL;
return true;
}else {
Node *ccc = head->next;
// 后节点的前指针
head->next->next->prev = head;
// 前节点的后指针
head->next = head->next->next;
free(ccc);
return true;
}
}
}
}
int main() {
NodeList L;
if (InitList(L)) {
printf("\n初始化成功\n");
}else {
printf("\n初始化失败\n");
}
if (EmptyList(L)){
printf("\n此表为空表\n");
}else {
printf("\n此表非空\n");
}
printf("\n表长度: %d\n", Length(L));
printf("\n在第1个位置插入111\n");
if (addList(L, 1, 111)){
printf("\n插入成功");
}else {
printf("\n插入失败");
}
printf("\n打印链表\n");
output(L);
printf("\n在第2个位置插入222\n");
if (addList(L, 2, 333)){
printf("\n插入成功");
}else {
printf("\n插入失败");
}
printf("\n打印链表\n");
output(L);
printf("\n在第1个位置插入444\n");
if (addList(L, 1, 444)){
printf("\n插入成功");
}else {
printf("\n插入失败");
}
printf("\n打印链表\n");
output(L);
printf("\n在第1个位置插入444\n");
if (addList(L, 4, 555)){
printf("\n插入成功");
}else {
printf("\n插入失败");
}
printf("\n打印链表\n");
output(L);
fanzhuan(L);
printf("\n删除第4个位置的e\n");
int e = -1;
if (DeleteList(L, 1, e)) {
printf("\n删除成功第2个位置的: %d\n", e);
}else {
printf("\n删除失败\n");
}
printf("\n打印链表\n");
output(L);
fanzhuan(L);
}