#include<stdio.h>
#include<stdlib.h>
/*数据结构:存放数据的一种结构*/
/*结构体:秒速的是数据的结构单元*/
/*结构体复杂,但是当我们把单个结点拿出来分析,就不复杂了*/
struct Node
{
int data;
struct Node*left; /*左指针和右指针*/
struct Node*right;.
};
//创建节点
struct Node*creatNode(int data)
{
struct Node*newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode ->left = newNode->right = NULL;
return newNode;
}
struct List
{
lint size;
struct Node*firstNode;/*第一个与第二个结点*/
struct Node*lastNode;
}
struct List * createList()
{
struct List*list = (struct Node*)malloc(sizeof(struct List));
list->size = 0;
list->firstNode = list -> lastNode = NULL;
return list;
}
//表头插入
void insertNodeByHead(struct List* list , int data)
{
struct Node*newNode = createNode(data);
if(list->firstNode == NULL)
{
list->firstNode = newNode;/*只有这个结点时,即使表头又是表尾*/
list->lastNod = newNode;
list->firstNode = newNode;
}
else
{
list->firstNode->left = newNode;
newNode->right = list->firstNode;
list->firstNode = newNode;/*表头法插入在这里只有两条线,即两个指针指向,另外两条为NULL*/
}
list->size++;
}
//表尾插入,和表头发插入一样
void insertNodeByTail(struct List*list, int data)
/*和前面的单链表差不多*/
{
struct Node*newNode = createNode(data);
if(list->lastNode == NULL)
{
list -> firstNode = newNode;/*头结点*/
}
else
{
list->lastNode->right = newNode;/*建立双向指定*/
newNode->left = list->lastNode;
}
list->lastNode=newNode;/*表尾移动*/
list->size++;
}
//指定位置插入
void isertNodeByAppoin(struct List*list,int data,int posData)
{
if(list->size == 0)//如果是空的,就是表头法插入
{
printf("链表为空,无法插入!");
return;
}
else if(list->firstNode->data == posData)/*第一个节点正好等于指定位点的数据,那就是表头法插入*/
{
insertNodeByHead(list,data);
}
else
{
struct Node*posNode = list->firstNode->right;
struct Node*posNodeLeft = list->firstNode;
while(posNode !=NULL&&posNode->data != posData)
{
posNodeLeft = posNode;
posNode = posNode->right;
}
if(posNode == NULL)
{
printf("未找到相应位置,无法插入!");
return;
}
else
{
struct Node*newNode = createNode(data);
posNodeLeft->right = newNode;
newNode->left = posNodeLeft;
newNode->right = posNode;
posNode ->left = newNode;
}
}
}
//求大小,判断size是否为NULL
int listSize(struct List*list) /*其实现在我搞不懂这是干嘛的*/
{
return list->size;
}
int emptyList(struct List*list)
{
if(list->size==0)
return 0;
else
return1;
}
void printListByRight(struct List*list)
{
if(list->size == 0)
printf("无法打印,链表为空!");
else
{
struct Node* pMove = list->firstNode;
while(pMove)
{
printf("%d",pMove->data);
pMove = pMove->right;
}
}
printf("\n");
}
void printListByLeft(struct List*list)
{
if(list->size==0)
printf("无法打印,链表为空!");
else
{
struct Node*pMove = list->lastNode;
while(pMove)
{
printf("%d",pMove->data);
pMove = pMove->left;
}
}
print("\n");
}
int main()
{
struct List*list = createList();
inserNodeByHead(list,3);
inserNodeByHead(list,2);
inserNodeByHead(list,1);
printListByLeft(list); //左往右插
printListByRight(list);//右往左插
insertNodeByAppoin(list,200,100);/*在100前面插入200*/
printListByLeft(list);
printListByRight(list);
system("pause");
return 0;
}
双向链表
最新推荐文章于 2025-05-02 21:45:54 发布