双链表基本操作实现
Posted 银背欧尼酱
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了双链表基本操作实现相关的知识,希望对你有一定的参考价值。
pra.c**
#include "pra.h"
#include <stdio.h>
#include <malloc.h>
#include <assert.h>
//创造节点
Node* BuyDListNode(DataType data)
{
Node* newnode = (Node*)malloc(sizeof(Node));
if (NULL == newnode)
{
assert(0);
return NULL;
}
newnode->data = data;
newnode->next = NULL;
newnode->prev = NULL;
return newnode;
}
//初始化
void DListInit(Node** head)
{
assert(head);
*head = BuyDListNode(0);
(*head)->next = *head;
(*head)->prev = *head;
}
//在pos前插入
void DListInsert(Node* pos, DataType data)
{
Node* newNode = NULL;
if (NULL == pos)
return;
newNode = BuyDListNode(data);
newNode->prev = pos->prev;
newNode->next = pos;
newNode->prev->next = newNode;
pos->prev = newNode;
}
//删除pos
void DListErase(Node* pos)
{
if (pos == NULL)
return;
pos->prev->next = pos->next;
pos->next->prev = pos->prev;
free(pos);
}
//头插
void DListPushFront(Node* head, DataType data)
{
DListInsert(head->next, data);
//头删
}
void DListPopFront(Node* head)
{
Node* cur = head;
DListErase(cur->next);
}
//尾插
void DListPushBack(Node* head, DataType data)
{
DListInsert(head, data);
}
//尾删
void DListPopBack(Node* head)
{
DListErase(head->prev);
}
//消除链表
void DListDestroy(Node** head)
{
Node* cur = (*head)->next;
while (cur != (*head))
{
(*head)->next = cur->next;
free(cur);
cur = (*head)->next;
}
free(*head);
*head = NULL;
}
//打印链表
void PrintDList(Node* head)
{
Node* cur = head->next;
while (cur != head)
{
printf("%d ", cur->data);
cur = cur->next;
}
printf("\\n");
}
//测试程序
void TestDList()
{
Node* head = NULL;
DListInit(&head);
DListPushBack(head, 1);
DListPushBack(head, 2);
DListPushBack(head, 3);
DListPushBack(head, 4);
DListPushBack(head, 5);
DListPushBack(head, 6);
PrintDList(head);
DListPushFront(head, 0);
PrintDList(head);
DListPopFront(head);
PrintDList(head);
DListPopBack(head);
DListPopBack(head);
DListPopBack(head);
PrintDList(head);
DListDestroy(&head);
}
pra.h
#pragma once
typedef int DataType;
typedef struct DListNode
{
struct DListNode* next;
struct DListNode* prev;
DataType data;
}Node;
void DListInit(Node** head);
void DListPushFront(Node* head, DataType data);
void DListPopFront(Node* head);
void DListPushBack(Node* head, DataType data);
void DListPopBack(Node* head);
void DListInsert(Node* pos, DataType data);
void DListErase(Node* pos);
void DListDestroy(Node** head);
Node* BuyDListNode(DataType data);
void PrintDList(Node* head);
//
void TestDList();
以上是关于双链表基本操作实现的主要内容,如果未能解决你的问题,请参考以下文章