数据结构之双向链表的实现

本文详细介绍了双向链表的结构与实现方法,包括创建、遍历(正向与反向)、查找、插入及删除等核心操作。通过具体代码示例展示了如何有效地管理和操作双向链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

*****双向链表的实现*****



双链表就可以看成两个单链表组合成的,只是相比单链表而言,它能从两个方向进行遍历链表,目前还不知道这有什么
优势,因为当我们想查找一个元素时,并不知道一个有序的链表里面这个被查找的元素离哪一边较近。



1)双链表的结构与单链表有点不一样,它要保证从链表的任意一端都能遍历链表,所以下面是双链表里面的结点的结构:

typedef structdouList
{
               struct douList *prior;
               struct douList *next;
               int data;
}DouList;

2)双向链表的创建,并初始化:

DouList *Creat_List()
{
               DouList *root = NULL;
               DouList *pre = NULL;
               DouList *cur = NULL;
               int data = 0;
               int i = 0;
 
 
               root = (DouList*)malloc(sizeof(DouList));
               if(NULL == root)
               {
                               printf("ERROR:Can't malloc the root.\n");
                               exit(ERROR);
               }
               root->next = NULL;
               root->prior = NULL;
 
 
               pre = root;
               while(++i <= 10)
               {
                               cur = (DouList*)malloc(sizeof(DouList));
                               if(NULL == cur)
                               {
                                              printf("ERROR:Can't malloc the current List\n");
                                              exit(ERROR);
                               }
 
 
                               //init the cur
                               cur->next =NULL;
                               cur->prior =NULL;
                               cur->data =2*i - 1;
 
 
                               //connect theDoubly Linked List
                               pre->next =cur;
                               cur->next =NULL;
                               if(pre == root)
                               {
                                              cur->prior= NULL;
                                              pre->prior= NULL;
                                              pre->prior= cur;
                               }
                               else
                               {
                                              root->prior= cur;
                                              cur->prior= pre;
                               }
                               pre = cur;
               }
 
 
               return root;
}

2)双向链表的遍历:

<1>正向遍历,即以next方向遍历:

voidShow_NextList(DouList *root)
{
               DouList *pre = root->next;
 
 
               printf("This is the doublylinked list in the next order;\n");
               while(NULL != pre)
               {
                               printf("%d\n",pre->data);
                               pre =pre->next;
               }
}

<2>反向遍历,即以prior方向遍历:

voidShow_PriorList(DouList *root)
{
               DouList *pre = root->prior;
 
 
               printf("This is the doublylinked list in the prior order;\n");
               while(NULL != pre)
               {
                               printf("%d\n",pre->data);
                               pre =pre->prior;
               }
}

3)查找结点,同样这里只实现返回结点:

<1>正向查找:

DouList*Find_NextList(DouList *root)
{
               DouList *cur = root->next;
               int data;
 
 
               printf("Enter a data youwant to find in next order:\n");
               scanf("%d",&data);
 
 
               while(NULL != cur)
               {
                               if(data ==cur->data)
                               {
                                              returncur;
                               }
                               cur =cur->next;
               }
 
 
               return NULL;
}

<2>反向查找:

DouList*Find_PriorList(DouList *root)
{
               DouList *cur = root->prior;
               int data;
 
 
               printf("Enter a data youwant to find in prior order:\n");
               scanf("%d",&data);
 
 
               while(NULL != cur)
               {
                               if(data ==cur->data)
                               {
                                              returncur;
                               }
                               cur =cur->prior;
               }
 
 
               return NULL;
}

4)插入新结点:(仅实现了next方向的插入)

DouList*Insert_List(DouList *root)
{
               DouList *cur = root->next;
               DouList *pre = root;
               int data = 0;
               DouList *newList = NULL;
 
 
               printf("Enter the data youwant to insert:\n");
               scanf("%d",&data);
 
 
               newList = (DouList*)malloc(sizeof(DouList));
               if(NULL == newList)
               {
                               printf("ERROR:Can't malloc the new List.\n");
                               exit(ERROR);
               }
 
 
               newList->data = data;
               newList->next = NULL;
               newList->prior = NULL;
 
 
               while(NULL != cur->next)
               {
                               //find thelocation which need to be inserted
                               if(data < cur->data)
                               {
                                              //ifthe new List in the front of the first List(except the root)
                                              if(root->next== cur)
                                              {
                                                             root->next= newList;
                                                             newList->next= cur;
                                                             newList->prior= NULL;
                                                             cur->prior= newList;
                                              }
                                              //ifthe new List in the front of the last List
                                              //whenin the order of next
                                              else
                                              {
                                                             pre->next= newList;
                                                             newList->next= cur;
                                                             newList->prior= pre;
                                                             cur->prior= newList;
                                              }
 
 
                                              break;
                               }
                               //move thepointer to the doubly linked list
                               else
                               {
                                              pre= cur;
                                              cur= cur->next;
                               }
               }
 
 
               if(NULL == cur->next)
               {
                               //insert the newList in the front of last List
                               if(data <cur->data)
                               {
                                              pre->next= newList;
                                              newList->next= cur;
                                              cur->prior= newList;
                                              newList->prior= pre;
                               }
                               //insert the newList in the last List
                               else
                               {
                                              cur->next= newList;
                                              newList->next= NULL;
                                              newList->prior= cur;
                                              root->prior= newList;
                               }
               }
 
 
               //insert successe
               return newList;
}

5)删除结点:(仅实现了以next的方向)

DouList*Delete_List(DouList *root)
{
               DouList *cur = root->next;
               DouList *pre = root;
               DouList *deleteList = NULL;
               int data;
 
 
               printf("Enter a data youwant to delete:\n");
               scanf("%d",&data);
 
 
               while(NULL != cur->next)
               {
                               if(data ==cur->data)
                               {
                                              deleteList= cur;
 
 
                                              //ifthe list to delete is in the first List(except the root)
                                              if(root->next== cur)
                                              {
                                                             cur->next->prior= NULL;
                                                             root->next= cur->next;
                                              }
                                              //ifthe list to delete isn't in the first List(except the root)
                                              else
                                              {
                                                             pre->next= cur->next;
                                                             cur->next->prior= pre;
                                              }
                                              free(cur);
                                             
                                              //thedeleteList is connected with the cur
                                              //whencur was free,deleteList will become shakable
                                              //shouldinit the deleteList to let the return's use
                                              deleteList->next= NULL;
                                              deleteList->prior= NULL;
                                              deleteList->data= data;
                                             
                                              returndeleteList;
                               }
                               else
                               {
                                              pre= cur;
                                              cur= cur->next;
                               }
               }
 
 
               //when the list to delete is inthe last List
               if(data == cur->data)
               {
                               deleteList = cur;
                               pre->next =NULL;
                               root->prior =pre;
                              
                               free(cur);
 
 
                               deleteList->next= NULL;
                               deleteList->prior= NULL;
                               deleteList->data= data;
                               returndeleteList;
               }
 
 
               return NULL;
}

*****总结*****

这次能够实现这两种链表的功能,这要靠两种工具:
(1)严老师的《数据结构》一书,里面提供了链表实现的各种的思想基础
(2)调试,以前总看别人写的东西都说C程序员必须学会调试,这次实现这些东西的一大利器
就是它了,初次使用调试来解决指针问题,真心觉得它的前途无限。

 

 

 

### 使用Transformer模型进行图像分类的方法 #### 方法概述 为了使Transformer能够应用于图像分类任务,一种有效的方式是将图像分割成固定大小的小块(patches),这些小块被线性映射为向量,并加上位置编码以保留空间信息[^2]。 #### 数据预处理 在准备输入数据的过程中,原始图片会被切分成多个不重叠的patch。假设一张尺寸为\(H \times W\)的RGB图像是要处理的对象,则可以按照设定好的宽度和高度参数来划分该图像。例如,对于分辨率为\(224\times 224\)像素的图像,如果选择每边切成16个部分的话,那么最终会得到\((224/16)^2=196\)个小方格作为单独的特征表示单元。之后,每一个这样的补丁都会通过一个简单的全连接层转换成为维度固定的嵌入向量。 ```python import torch from torchvision import transforms def preprocess_image(image_path, patch_size=16): transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), # 假设目标分辨率是224x224 transforms.ToTensor(), ]) image = Image.open(image_path).convert('RGB') tensor = transform(image) patches = [] for i in range(tensor.shape[-2] // patch_size): # 高度方向上的循环 row_patches = [] for j in range(tensor.shape[-1] // patch_size): # 宽度方向上的循环 patch = tensor[:, :, i*patch_size:(i+1)*patch_size, j*patch_size:(j+1)*patch_size].flatten() row_patches.append(patch) patches.extend(row_patches) return torch.stack(patches) ``` #### 构建Transformer架构 构建Vision Transformer (ViT),通常包括以下几个组成部分: - **Patch Embedding Layer**: 将每个图像块转化为低维向量; - **Positional Encoding Layer**: 添加绝对或相对位置信息给上述获得的向量序列; - **Multiple Layers of Self-Attention and Feed Forward Networks**: 多层自注意机制与前馈神经网络交替堆叠而成的核心模块; 最后,在顶层附加一个全局平均池化层(Global Average Pooling)以及一个多类别Softmax回归器用于预测类标签。 ```python class VisionTransformer(nn.Module): def __init__(self, num_classes=1000, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4., qkv_bias=False, drop_rate=0.): super().__init__() self.patch_embed = PatchEmbed(embed_dim=embed_dim) self.pos_embed = nn.Parameter(torch.zeros(1, self.patch_embed.num_patches + 1, embed_dim)) self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) dpr = [drop_rate for _ in range(depth)] self.blocks = nn.Sequential(*[ Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop=dpr[i], ) for i in range(depth)]) self.norm = nn.LayerNorm(embed_dim) self.head = nn.Linear(embed_dim, num_classes) def forward(self, x): B = x.shape[0] cls_tokens = self.cls_token.expand(B, -1, -1) x = self.patch_embed(x) x = torch.cat((cls_tokens, x), dim=1) x += self.pos_embed x = self.blocks(x) x = self.norm(x) return self.head(x[:, 0]) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值