一、双向链表的介绍

  一种更复杂的链表是“双向链表”或“双面链表”。每个节点有两个链接:一个指向前一个节点,当此节点为第一个节点时,指向空值;而另一个指向下一个节点,当此节点为最后一个节点时,指向空值。

  

  上图是双向链表的结构图,即通过上一个节点可以找到下一个,通过下一个也可以找到上一个节点。

二、双向链表插入和删除的图解

  1、插入图解

  

  2、删除图解

  

三、双向链表的python代码实现

# 1、创建节点
class Node(object):
# 初始化方法
def __init__(self, item):
self.item= item
self.next = None
self.prev = None # 2、创建循环链表
class DoubleLinKList(object):
# 初始化方法
def __init__(self):
self._head = None # 3、判断是否为空
def is_empty(self):
"""判断链表是否为空"""
return self._head == None # 4、求其长度
def length(self):
"""返回链表的长度"""
cur = self._head
count = 0
while cur != None:
count += 1
cur = cur.next
return count # 遍历
def travel(self):
"""遍历链表"""
print("你要遍历的链表元素有:",end=" ")
cur = self._head
while cur != None:
print("%s "%cur.item,end=" ")
cur = cur.next
print("") # 5、头插
def add(self, item):
"""头部插入元素"""
node = Node(item)
if self.is_empty():
# 如果是空链表,将_head指向node
self._head = node
else:
# 将node的next指向_head的头节点
node.next = self._head
# 将_head的头节点的prev指向node
self._head.prev = node
# 将_head 指向node
self._head = node # 6、尾插
def append(self, item):
"""尾部插入元素"""
node = Node(item)
if self.is_empty():
# 如果是空链表,将_head指向node
self._head = node
else:
# 移动到链表尾部
cur = self._head
while cur.next != None:
cur = cur.next
# 将尾节点cur的next指向node
cur.next = node
# 将node的prev指向cur
node.prev = cur # 7、查找
def search(self, item):
"""查找元素是否存在"""
cur = self._head
while cur != None:
if cur.item == item:
return True
cur = cur.next
return False # 8、指定位置插入
def insert(self, pos, item):
"""在指定位置添加节点"""
if pos <= 0 or pos>self.length()+1 :
print("你输入的位置有误,请重新输入")
elif pos == 1:
self.add(item)
elif pos == self.length()+1:
self.append(item)
else:
node = Node(item)
cur = self._head
count = 1
# 移动到指定位置的前一个位置
while count < (pos - 1):
count += 1
cur = cur.next
# 将node的prev指向cur
node.prev = cur
# 将node的next指向cur的下一个节点
node.next = cur.next
# 将cur的下一个节点的prev指向node
cur.next.prev = node
# 将cur的next指向node
cur.next = node # 9、删除
def remove(self, item):
"""删除元素"""
if self.is_empty():
return
else:
cur = self._head
if cur.item == item:
# 如果首节点的元素即是要删除的元素
if cur.next == None:
# 如果链表只有这一个节点
self._head = None
else:
# 将第二个节点的prev设置为None
cur.next.prev = None
# 将_head指向第二个节点
self._head = cur.next
return
while cur != None:
if cur.item == item:
# 将cur的前一个节点的next指向cur的后一个节点
cur.prev.next = cur.next
# 将cur的后一个节点的prev指向cur的前一个节点
cur.next.prev = cur.prev
break
cur = cur.next # 验证
if __name__ == '__main__': double_link = DoubleLinKList()
# 头插
double_link.add(1)
# 遍历
double_link.travel()
# 尾插
double_link.append(2)
double_link.travel()
# 按照索引插入
double_link.insert(3,4)
double_link.travel() double_link.insert(3,3)
double_link.travel()
# 删除
double_link.remove(3)
double_link.travel()

运行结果为:

你要遍历的链表元素有: 1
你要遍历的链表元素有: 1 2
你要遍历的链表元素有: 1 2 4
你要遍历的链表元素有: 1 2 3 4
你要遍历的链表元素有: 1 2 4

四、双向链表的C语言代码实现

//  main.m
// 双向链表
// Created by 侯垒 on 2019/6/28.
// Copyright © 2019 可爱的侯老师. All rights reserved. #import <Foundation/Foundation.h>
typedef struct N
{
int element;
struct N *next;
struct N *prev;
}Node; // 创建节点
Node *createNode(int num)
{
Node *node = (Node *)malloc(sizeof(Node));
node->element = num;
node->next = NULL;
node->prev = NULL;
return node;
} // 创建双向链表
Node *createDoubleLinkList(Node *node)
{
Node *head = node;
return head;
} // 判断是否为空
int is_empty(Node *head)
{
if (head == NULL)
{
return ;
}
else
{
return ;
}
} // 求其长度
int length(Node *head)
{
Node *current = head;
int count = ;
while (current != NULL)
{
count++;
current = current->next;
}
return count;
} // 遍历
void travel(Node *head)
{
printf("你要遍历的数据有:");
Node *current = head;
while (current != NULL)
{
printf("%d ",current->element);
current = current->next;
}
printf("\n");
} // 头插
Node * add(Node *head,int num)
{
Node *node = createNode(num);
if (is_empty(head)==)
{
head = node;
}
else
{
node->next = head;
head->prev = node;
head = node;
}
return head;
} // 尾插
Node* append(Node *head,int num)
{
Node *node = createNode(num);
if (is_empty(head)==)
{
head = node;
}
else
{
Node *current = head;
while (current->next != NULL)
{
current = current->next;
}
current->next = node;
node->prev = current;
}
return head;
} // 查找
int search(Node *head,int num)
{
Node *current = head;
for (int i=; i<length(head); i++)
{
if (current->element == num)
{
return i+;
}
current = current->next;
}
return ;
} // 按指定位置插入
Node * insert(Node *head ,int index,int num)
{
if (index<=||index>length(head)+)
{
printf("你要插入的位置不对,请重新插入");
}
else if (index == )
{
head = add(head, num);
}
else if (index == length(head)+)
{
append(head, num);
}
else
{
Node *node = createNode(num);
Node *current = head;
for (int i=; i<index-; i++)
{
current = current->next;
}
node->prev = current;
node->next = current->next;
current->next->prev = node;
current->next = node;
}
return head;
} // 删除元素
Node * removeNode(Node *head,int num)
{
if (is_empty(head)==)
{
printf("你要删除的链表为空");
}
else
{
Node *current = head;
//处理头结点就是要删除的节点
if (current->element == num)
{
if (current->next == NULL)
{
// 只有首节点这一个元素
head = NULL;
}
else
{
// 要删除的是首节点,但是后面还有元素
current->next->prev = NULL;
head = current->next;
}
}
else
{
while (current!=NULL)
{
if (current->element == num)
{
current->prev->next = current->next;
current->next->prev = current->prev;
break;
}
current = current->next;
}
}
}
return head;
} int main(int argc, const char * argv[]) { // 创建节点
Node *node = createNode();
// 创建链表
Node *head = createDoubleLinkList(node);
// 验证遍历
travel(head);
// 验证头插
head = add(head, );
travel(head);
// 验证尾插
head = append(head, );
travel(head); // 验证查找
int index = search(head, );
if (index != )
{
printf("你要查找的数据在%d位置\n",index);
}
else
{
printf("没有找到你要的数据\n");
} //验证按指定位置插入
head = insert(head, , );
travel(head); //验证删除
head = removeNode(head, );
travel(head);
return ;
}

运行结果为:

你要遍历的数据有:
你要遍历的数据有:
你要遍历的数据有:
你要查找的数据在2位置
你要遍历的数据有:
你要遍历的数据有:

python算法与数据结构-双向链表(40)的更多相关文章

  1. Python算法与数据结构--求所有子数组的和的最大值

    Python算法与数据结构--求所有子数组的和的最大值 玄魂工作室-玄魂 玄魂工作室秘书 玄魂工作室 昨天 题目:输入一个整形数组,数组里有正数也有负数.数组中连续的一个或多个整数组成一个子数组,每个 ...

  2. python算法与数据结构-算法介绍(31)

    一.算法和数据结构 什么是算法和数据结构?如果将最终写好运行的程序比作战场,我们程序员便是指挥作战的将军,而我们所写的代码便是士兵和武器. 那么数据结构和算法是什么?答曰:兵法!故,数据结构和算法是一 ...

  3. python算法与数据结构-单链表(38)

    一.链表 链表是一种物理存储单元上非连续.非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的.链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成.每个结点包括 ...

  4. python算法与数据结构-栈(43)

    一.栈的介绍 栈作为一种数据结构,是一种只能在一端进行插入和删除操作.它按照先进后出的原则存储数据,先进入的数据被压入栈底,最后的数据在栈顶,需要读数据的时候从栈顶开始弹出数据(最后一个数据被第一个读 ...

  5. python算法与数据结构-队列(44)

    一.队列的介绍 队列的定义:队列是一种特殊的线性表,只允许在表的头部(front处)进行删除操作,在表的尾部(rear处)进行插入操作的线性数据结构,这种结构就叫做队列.进行插入操作的一端称为队尾,进 ...

  6. python算法与数据结构-数据结构中常用树的介绍(45)

    一.树的定义 树是一种非线性的数据结构,是由n(n >=0)个结点组成的有限集合.如果n==0,树为空树.如果n>0,树有一个特定的结点,根结点根结点只有直接后继,没有直接前驱.除根结点以 ...

  7. python算法与数据结构-二叉树的代码实现(46)

    一.二叉树回忆 上一篇我们对数据结构中常用的树做了介绍,本篇博客主要以二叉树为例,讲解一下树的数据结构和代码实现.回顾二叉树:二叉树是每个节点最多有两个子树的树结构.通常子树被称作“左子树”(left ...

  8. python算法与数据结构-冒泡排序算法(32)

    一.冒泡排序介绍 冒泡排序(英语:Bubble Sort)是一种简单的排序算法.它重复地遍历要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来.遍历数列的工作是重复地进行直到没有再需要 ...

  9. python算法与数据结构-选择排序算法(33)

    一.选择排序的介绍 选择排序(Selection sort)是一种简单直观的排序算法.首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素, ...

随机推荐

  1. python 读写XLS

    需要库: xlrd, xlwt, xlutils 导入 import xlrd from xlutils.copy import copy 打开文件 data = xlrd.open_workbook ...

  2. 解决:eth0安装插卡无法自己主动,网卡的配置信息不network-scripts于

    问题方案:eth0安装插卡无法自己主动,网卡的配置信息不network-scripts于 解决: 1>vi /etc/rc.d/rc.loacl 最后加 ifup eth0 2>reboo ...

  3. Delphi Bpl包学习

    对于BPL包,我个人理解是:就是一种封装方式,和DLL,EXE类似,把代码放到包(package)里面保存而已. 一.先说说如何创建BPL包 1.   打开delphi IDE(delphi7 为例) ...

  4. A Byte of Python(简明Python教程) for Python 3.0 下载

    A Byte of Python v1.92 (for Python 3.0) 官方下载地址,当前(20120730)  最新版本 1.92 基于Python3的 下载: http://files.s ...

  5. 跟我学ASP.NET MVC之九:SportsStrore产品管理

    摘要: 在这篇文章中,我将继续完成SportsStore应用程序,让站点管理者可以管理产品列表.我将添加创建.修改和删除产品功能. 本篇文章将分模块的方式,逐个介绍SportsStore站点管理功能的 ...

  6. ASP.NET Core Identity 配置 - ASP.NET Core 基础教程 - 简单教程,简单编程

    原文:ASP.NET Core Identity 配置 - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core Identity 配置 上一章节我们简单介绍了下 Id ...

  7. Monthly Expense

    Problem Description Farmer John is an astounding accounting wizard and has realized he might run out ...

  8. Headless Chrome入门

    原文地址:Getting Started with Headless Chrome  By EricBidelman  Engineer @ Google working on web tooling ...

  9. cocos2D-X从的源代码的分析cocos2D-X学习OpenGL(1)----cocos2D-X渲染架构

     个人原创.欢迎转载,转载请注明原文地址http://blog.csdn.net/bill_man 从本篇文章開始,将分析cocos2D-X 3.0源码,第一部分是从cocos2D-X学习OpenGL ...

  10. IIS运行WCF服务报错

    试图加载格式不正确的程序   image 解决方法   image HTTP 错误 500.19   image 解决方法在控制面板————>程序————>启用或关闭windows功能—— ...